2013-06-19 3 views
0

내 모든 contracts_controller_spec.rb 테스트가 하나를 제외하고 통과합니다.컨트롤러 사양 '모델 확인 유효성 검사'

그것은이 실패 : 여기

ContractsController #create redirects to show page when given valid params. 
Failure/Error: expect(assigns[:contract].valid?).to be_true # factory is missing 
# code_id and maybe others, check model validations 
    expected: true value 
     got: false 

내 모델 :

class Contract < ActiveRecord::Base 
    belongs_to :employee 
    belongs_to :client 
    belongs_to :primary_care_manager 
    belongs_to :code 
    has_many :schedules 


    attr_accessible :authorization_number, :start_date, :end_date, :client_id, 
    :units, :contracted_units, :frequency, :code_id, :primary_care_manager_id, 
    :employee_id, :employee_flag 

    validates_presence_of :authorization_number, :start_date, :end_date, 
    :units, :contracted_units, :frequency, :code_id 

    validates_presence_of :client_id, :primary_care_manager_id, unless: Proc.new { |a| 
    a.employee_flag } 
    validates_presence_of :employee_id, if: Proc.new { |a| a.employee_flag } 

여기에 실패 내 contracts_controller_spec.rb 테스트의 예입니다 : 마지막으로

it "#create redirects to show page when given valid params." do 
    contract = attributes_for(:contract) 
    post :create, contract: contract 
    expect(assigns[:contract]).to be_a Contract 
    expect(assigns[:contract].valid?).to be_true # factory is missing code_id and maybe 
      # others, check model validations 
    expect(response).to be_redirect 
    expect(response).to redirect_to contract_path(id: assigns[:contract].id) 
    end 

, 여기 내 공장 .rb 파일

factory :contract do 
    association :employee,    factory: :employee 
    association :client,    factory: :client 
    association :code,     factory: :code 
    association :primary_care_manager, factory: :primary_care_manager 
    sequence(:authorization_number)  { |n| "20007000-#{'%03d' % n}" } 
    start_date       Date.today 
    end_date       Date.today.next_month 
    units        "15 minutes" 
    contracted_units     "20" 
    frequency       "weekly" 
    employee_flag      true 
    end 

은 내가 tail.test.log을 확인했고, 외국 키를 생성하는 동안 그들은이 예제가 실행되는 시간에 사용할 수없는 것을 보았다 :

it "#create redirects to show page when given valid params." do 

누군가가 나를 도와주세요 수 내 컨트롤러 테스트에서 위 예제를 실행할 때 외래 키가 나타날 수있는 타이밍을 얻을 수 있도록이 테스트를 작성하는 방법을 이해해야한다.

감사합니다.

답변

1

attributes_for은 관련 팩토리에 ID를 할당하지 않습니다. 반면에 Factory.build은 연관된 팩토리에 대한 ID를 할당하지 않습니다. 대신

contract = Factory.build(:contract).attribues.symbolize_keys 

:

contract = attributes_for(:contract) 

그러나 협회와 build를 사용하는 단점이있다

그래서 당신은 뭔가를 할 수 있습니다. 관련 객체의 ID를 생성하기 위해 FactoryGirl은 연관된 객체를 생성합니다. 따라서 build은 일반적으로이 경우 데이터베이스에 도달하지 않지만 각 객체에 대해 레코드를 삽입합니다. 그게 중요하다면 build_stubbed 최신 방법을 확인해보십시오. http://robots.thoughtbot.com/post/22670085288/use-factory-girls-build-stubbed-for-a-faster-test을 참조하십시오.

+0

감사합니다. @steve ... '최신 build_stubbed'메소드를 확인합니다. – thomasvermaak