如何测试我在rails中正确设置了多对多关系?

时间:2012-05-10 10:21:13

标签: ruby-on-rails testing activerecord

我正在使用: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

我确信我只是误解了一些事情。非常感谢任何指针。

2 个答案:

答案 0 :(得分:2)

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

class MenuItem < ActiveRecord::Base
  belongs_to :product #burger
  belongs_to :addition #extra mustard
end

答案 1 :(得分:0)

相关问题