控制器规格'检查模型验证'

时间:2013-06-19 19:14:54

标签: validation rspec

除了一个,我的所有contract_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

最后,这是我的factory.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 个答案:

答案 0 :(得分: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