简体   繁体   中英

Factory Girl with implicit has_many association

I'm trying to test a model that has an implicit has_many association, and am having some difficulties.

I have a table A, with column B_ID, where B is basically a foreign key - except there is no table B in my database, or an active record class associated with object B. There is also table C that has column a B_ID.

In the model for table C we have:

# implicit has_many :alphas
def alphas
   Alpha.where(:b_id => b_id).order(:xyz)
end

This database structure makes sense for the data I have, and the non-test code works fine.

My test code almost works, and I hope I am just missing something simple.

I have factories defined for A and C, and I have a test:

a1 = Factory(:alpha, :b_id => 123, :xyz => 100)
a2 = Factory(:alpha, :b_id => 123, :xyz => 200)
c1 = Factory(:c, :b_id => 123)

puts c1.alphas.count
puts c1.alphas.first

c1.alphas.first.should == a1

The output is:

2
nil
<test fails>

Changing the number of A objects that share the B_ID result in the c1.alphas.count changing, but I can't seem to actually inside the implicit association and get an A object back - instead I always get nil. There are other methods that in my C model that I can't test because those methods need to access fields on individual A objects.

Does anybody have any insight into what is going behind the scenes here, or what I might do to get around this? Thanks.

Take a look at this for an example to have an admin_user with the role of Admin.

https://github.com/drhenner/ror_ecommerce/blob/master/spec/factories/user.rb

In this case roles are not a factory.

I find it best to do this like the following though.

  @order = Factory(:order)
  order_item = Factory(:order_item, :total => 5.52 )
  @order.stubs(:order_items).returns([order_item, order_item])

or

  @order = Factory(:order)
  order_item = Factory(:order_item, :total => 5.52, :order => @order )

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