1

我正在学习 Rails 3,并开始进行单元测试。经过一番研究,我决定使用 MiniTest 进行单元测试。

我有以下型号

class Participant < ActiveRecord::Base

  ...

  # returns all items that were paid by participant  
  def paid_expenses
    self.items.where(:payee_id => self.id)
  end

  ...

end

我仍在研究如何对该方法进行单元测试。我想出了下面的测试用例。

class TestParticipant < MiniTest::Unit::TestCase

  def setup
    @participant = Participant.new
    @participant.first_name = "Elyasin"
    @participant.last_name = "Shaladi"
    @participant.email = "Elyasin.Shaladi@come-malaka.org"
    @participant.event_id = 1  
  end

  ...

  def test_paid_expenses
    @participant.save!
    item1 = @participant.items.create!( item_date: Date.today, amount: 10, currency: "EUR", exchange_rate: 1, base_amount: 10, payee_id: @participant.id, payee_name: @participant.name )
    item2 = Item.create!( item_date: Date.today, amount: 99, currency: "EUR", exchange_rate: 1, base_amount: 10, payee_id: 99, payee_name: "Other participant" )
    assert_includes @participant.paid_expenses, item1, "Participant's paid expenses should include items paid by himself/herself"
    refute_includes @participant.paid_expenses, item2, "Participant's paid expenses should only include items paid by himself/herself"  
  end

  ...

end

这就是我所取得的成就,但我并不真正感到满意。我有一种感觉,我可以做得比这更好。我在这里依赖 Item 对象,但理论上在单元测试中我不应该依赖外部因素。我认为“存根”、“模拟”等,但看不到如何正确处理:-(

你有没有更好的方法来做到这一点?我怎么能使用存根或模拟对象来做到这一点?

4

1 回答 1

0

我开始练习单元测试应该测试与外部因素隔离的模型/功能的假设。所以我决定对模型固有的外部行为进行存根。模型方法的单元测试Participant可能如下所示。

def test_paid_expense_items
  item1 = MiniTest::Mock.new
  items = MiniTest::Mock.new
  items.expect :where, [item1], [Hash]
  @participant.stub :items, items do
    assert_includes @participant.paid_expense_items, item1, "Participant's paid expenses should include items paid by himself/herself"
  end
end

到目前为止,我对这个解决方案很满意。但是,如果您认为您有更好的解决方案或补充信息或任何其他贡献,请随时发表评论。

于 2013-05-11T21:37:13.057 回答