测试一对多的关系工作

时间:2016-03-21 13:56:35

标签: ruby-on-rails minitest

在我的rails api中我有多个模型,有一对多的关系,我想要一种方法来测试我没有错过任何设置它们的任何东西。 Minitest中测试一对多关系是否设置正确的最佳方法是什么?我想看到的是,一张收据上可以有很多销售。

test 'multiple sales can have one receipt' do
 sale = Sale.new
 sale.receipt = 1234
 sale.save

 sale2 = Sale.new
 sale2.receipt = 1234
 sale2.save


 assert_equal sale.invoice_id, sale2.invoice_id, "receipts are not the same"
end

2 个答案:

答案 0 :(得分:1)

shoulda-matchers gem是我测试这样的协会的首选宝石。节省了手动测试关联的所有可能场景的乏味。

https://github.com/thoughtbot/shoulda

只需将gem添加到您的Gemfile中,您就可以编写测试,如...

class UserTest < Test::Unit::TestCase
  should have_many(:posts)
end

答案 1 :(得分:0)

我会这样测试:

test 'one receipt can have multiple sales' do
  receipt = Receipt.last
  sale1 = receipt.sales.create
  sale2 = receipt.sales.create

  assert receipt.sales.size > 1, "receipt should have multiple sales"
  assert_equal sale1.receipt, sale2.receipt, "receipts are not the same"
end