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

最后,这是我的 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

有人可以帮助我了解如何编写此测试,以便我有时间工作,以便在我在控制器测试中运行上述示例时显示外键。

谢谢。

4

1 回答 1

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

于 2013-06-20T08:11:49.660 回答