내 컨트롤러에 대한 표시 작업이 단위 테스트를 통과하지 않습니다. ControllerTest에서 오류가 발생합니다. 다음은 'rake test'에서 얻은 오류입니다.
> ERROR["test_should_get_show", TransactionsControllerTest, 2015-07-18
> 00:30:18 -0400] test_should_get_show#TransactionsControllerTest
> (1437193818.29s) ActiveRecord::RecordNotFound:
> ActiveRecord::RecordNotFound: Couldn't find Transaction with 'id'=
> app/controllers/transactions_controller.rb:21:in `show'
> test/controllers/transactions_controller_test.rb:6:in `block in <class:TransactionsControllerTest>'
> app/controllers/transactions_controller.rb:21:in `show'
> test/controllers/transactions_controller_test.rb:6:in `block in <class:TransactionsControllerTest>'
>
> 5/5:
> [=======================================================================================================================] 100% Time: 00:00:00, Time: 00:00:00
>
> Finished in 0.24993s 5 tests, 4 assertions, 0 failures, 1 errors, 0
> skips
이 오류에도 불구하고 http : // localhost : 3000 / transactions / 1 URL을 사용하면 브라우저에서 페이지가 성공적으로 생성됩니다.
그래서 어딘가에 오류가 있습니다. 실패하지 않습니다.
transaction_controller.rb
class TransactionsController < ApplicationController
def new
@transaction = Transaction.new
end
def create
@transaction = Transaction.new(transaction_params)
if @transaction.save
# Handle a successful save.
else
render 'new'
end
end
def index
@transactions = Transaction.all
end
def show
@transaction = Transaction.find(params[:id]) #this is row 21
end
private
def transaction_params
params.require(:transaction).permit(:company, :month, :account_code, :description, :transaction_amount)
end
end
transaction_controller_test.rb
require 'test_helper'
class TransactionsControllerTest < ActionController::TestCase
test "should get show" do
transaction = Transaction.create
get :show, id: transaction.id #this is row 6
assert_response :success
end
end
다음 설비는 레일에 의해 자동으로 생성되었습니다. 저는 Rails에 처음 왔고 제가 조명기구를 정말로 이해하지 못한다는 것을 인정해야합니다.
transaction.yml
one:
company: MyString
month: 2015-06-19
account_code: MyString
description: MyString
transaction_amount: 1.5
two:
company: MyString
month: 2015-06-19
account_code: MyString
description: MyString
transaction_amount: 1.5
내 경로 파일에서 루트를 인덱스 작업으로 설정하고 있습니다. http : // localhost : 3000 / transactions / 1 URL을 통해 show 작업에 액세스 할 계획 이며 위에서 언급했듯이 실제로 작동합니다.
route.rb
Rails.application.routes.draw do
root 'transactions#index'
resources :transactions
end
transaction.rb
class Transaction < ActiveRecord::Base
validates :month, presence: true
validates :account_code, presence: true
end
transaction_test.rb
require 'test_helper'
class TransactionTest < ActiveSupport::TestCase
def setup
#@transaction = transactions(:one)
@transaction = Transaction.new(company: "Inc", month: Date.new(2015,6,15).to_s,
account_code: "80-32100-12-1201-60010",
description: "Salaries & Wages - Histo Gross 1", transaction_amount: 100000)
end
test "should be valid" do
assert @transaction.valid?
end
test "month should be present" do
@transaction.month = " "
assert_not @transaction.valid?
end
test "account_code should be present" do
@transaction.account_code = " "
assert_not @transaction.valid?
end
test "month cannot be a string" do #not sure if this is worth anything at all
@transaction.month = "xxxxxxxxxxxx"
assert_not @transaction.valid?
end
end
Rails에서 생성 한 테스트 자동 (수정하기 전)은 매우 간단했습니다.
require 'test_helper'
class TransactionsControllerTest < ActionController::TestCase
test "should get show" do
get :show
assert_response :success
end
end
테스트가 먼저 트랜잭션을 생성 한 다음 어떻게 든 ID를 참조해야하기 때문에 위의 현재 버전으로 수정했습니다. 그러나 나는 이것을 올바르게했는지 잘 모르겠습니다.
Stackoverflow에서 이와 유사한 질문을 보았습니다. 예를 들어,이 질문은 도움이되었지만 저를 제대로 이해하지 못했습니다 . Count; ID가 Minitest 인 사용자 찾기
참고 : 처음에는 컨트롤러를 잘못 설정했습니다. 단일 "TransactionController"로 설정하고 복수 "TransactionsController"로 변경했습니다. 그래서 단위 테스트에서도 이름을 변경해야했습니다. 아마도 이것은 앱에 영향을 미쳤을 것입니다.
그래서 ... 질문 :
좋아, 그래서 coorasse의 제안은 create! 앱이 유효성 검사 오류를 발견하도록 강제했습니다. 초기 오류 ( 'id'= 인 트랜잭션을 찾을 수 없음)가 새 오류로 대체되었습니다.
ActiveRecord :: RecordInvalid : 유효성 검사 실패 : 월은 비워 둘 수 없으며 계정 코드는 비워 둘 수 없습니다.
모델 유효성 검사 오류를 생각하게 되었기 때문에 혼란 스러웠습니다. ControllerTest에서 모델 유효성 검사 오류가 발생하는 이유는 무엇입니까? 또한 transaction.rb 모델은 Month 및 AccountCode의 존재를 만족시키기 위해 유효성 검사를 추가했음을 명확하게 보여줍니다.
그래서 저는 RailsGuides http://guides.rubyonrails.org/testing.html 에있는 "A Guide to Testing Rails Applications"를 읽고 시간을 보냈습니다 . 섹션 8에서 끝까지, 각 코드 앞에 코드 블록을 포함하는 방법을 보여줍니다. 테스트. 다음은 새로운 transaction_controller_test입니다.
transaction_controller_test.rb (수정 됨)
require 'test_helper'
class TransactionsControllerTest < ActionController::TestCase
# called before every single test
def setup
@transaction = transactions(:one)
end
test "should get show" do
get :show, id: @transaction.id
assert_response :success
end
end
이 후 테스트를 통과했습니다! 불행히도 RailsGuides는 컨트롤러 테스트에서 설정을 사용하려는 이유를 알려주지 않습니다 . 현명한 Rails 전문가가 이에 대한 지침을 가지고 있다면 귀하의 의견을 주시면 감사하겠습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다