0

我正在使用 :through 方法建立多对多关系,并想测试我是否已正确设置所有内容。

class MenuItem < ActiveRecord::Base
  belongs_to :products #burger
  belongs_to :additions #extra mustard
end

产品就像汉堡包

class Product < ActiveRecord::Base
  has_many :menu_items
  has_many :additions, through: :menu_items
end

添加的东西就像额外的芥末或泡菜

class Addition < ActiveRecord::Base
  has_many :menu_items
  has_many :products, through: :menu_items
end

我已经设置了我的固定装置,以便一个汉堡包应该有 2 个与之相关的添加物。现在我想测试该关联是否有效。不完全确定如何执行此操作。我试过这个:

在夹具中,我将汉堡包的 id 设置为 22。还将汉堡包设置为芥末和泡菜(添加 2 个)。

test "product 22 should have 2 additions associated with it" do 
  menu_item = Product.find(22).additions
  assert_equal menu_item.count, 2 
end

我收到未初始化的常量错误

NameError: uninitialized constant Product::Additions

我确信我只是误解了一些东西。真的很感激任何指示。

4

2 回答 2

2

该错误是因为您需要对 belongs_to 使用单数。

class MenuItem < ActiveRecord::Base
  belongs_to :product #burger
  belongs_to :addition #extra mustard
end
于 2012-05-10T11:53:15.480 回答
0

检查shoulda-matchers宝石:https ://github.com/thoughtbot/should-matchers#activerecord-matchers

于 2012-05-10T10:28:42.133 回答