簡體   English   中英

具有隱式has_many關聯的Factory Girl

[英]Factory Girl with implicit has_many association

我正在嘗試測試具有隱式has_many關聯的模型,並且遇到了一些困難。

我有一個表A,其列B_ID,其中B基本上是一個外鍵-除了數據庫中沒有表B或與對象B相關聯的活動記錄類。還有一個表C,其列B_ID。

在表C的模型中,我們有:

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

這種數據庫結構對我擁有的數據有意義,並且非測試代碼可以正常工作。

我的測試代碼幾乎可以正常運行,我希望我只是缺少一些簡單的東西。

我為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

輸出為:

2
nil
<test fails>

更改共享B_ID的A對象的數量會導致c1.alphas.count發生更改,但我似乎無法真正進入隱式關聯內部並獲得A對象,而我總是得到nil。 在我的C模型中,我無法測試其他方法,因為這些方法需要訪問單個A對象上的字段。

是否有人對這里幕后發生的事情有什么了解,或者我可能會做些什么來解決這個問題? 謝謝。

以這個為例,以具有admin角色的admin_user為例。

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

在這種情況下,角色不是工廠。

我發現最好像下面這樣執行此操作。

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

要么

  @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