简体   繁体   中英

How to get the record in two way has_many association in factory Girl?

I am not able how to get record through event object just like 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

Here run the command in terminal

rspec spec/models/event_spec.rb

I get this error

/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 level too deep (SystemStackError)

For has_many and belongs_to association the FactoryGirl should be setup like this

event.rb

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

Factory files must have the same name to be used in association.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM