如何以两种方式获得记录has_many协会在工厂女孩?

时间:2017-01-06 17:31:02

标签: ruby-on-rails rspec

我无法像 event.bids

那样通过事件对象获取记录
class Event < ActiveRecord::Base
     has_many  :bids , dependent: :restrict_with_error
end
class Bid < ActiveRecord::Base
    belongs_to :event
end
factory :event do 
    after(:build) do |event|
      create(:bid, event: event)
    end
end
end
factory :bid do |f|
   f.association(:event)
end

此处在终端

中运行命令
rspec spec/models/event_spec.rb

我收到此错误

  

/home/aqib/.rbenv/versions/2.1.3/lib/ruby/gems/2.1.0/gems/activerecord-4.1.1/lib/active_record/connection_adapters/abstract/database_statements.rb:222:stack级别太深(SystemStackError)

1 个答案:

答案 0 :(得分:0)

对于has_many和belongs_to关联,FactoryGirl应该像这样设置

event.rb

FactoryGirl.define do
 factory :event do
  event_name 'some_name' #some attributes what you have in event model 
 end
end

工厂文件必须具有相同的名称才能使用。

bid.rb

FactoryGirl.define do
 factory :bid do
  bid_name 'some_name' #some attributes what you have in event model 
  event #for association
 end
end