简体   繁体   English

具有隐式has_many关联的Factory Girl

[英]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. 我正在尝试测试具有隐式has_many关联的模型,并且遇到了一些困难。

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. 我有一个表A,其列B_ID,其中B基本上是一个外键-除了数据库中没有表B或与对象B相关联的活动记录类。还有一个表C,其列B_ID。

In the model for table C we have: 在表C的模型中,我们有:

# 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: 我为A和C定义了工厂,并且进行了测试:

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. 更改共享B_ID的A对象的数量会导致c1.alphas.count发生更改,但我似乎无法真正进入隐式关联内部并获得A对象,而我总是得到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. 在我的C模型中,我无法测试其他方法,因为这些方法需要访问单个A对象上的字段。

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. 以这个为例,以具有admin角色的admin_user为例。

https://github.com/drhenner/ror_ecommerce/blob/master/spec/factories/user.rb 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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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