繁体   English   中英

使用MiniTest在Rails中对模型方法进行单元测试-如何使用存根或模拟对象?

[英]Unit testing a model method in Rails using MiniTest - How to use stubs or mock objects?

我正在学习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对象,但是从理论上讲,在单元测试中,我不应该依赖外部因素。 我以为是“存根”,“模拟”等,但看不到如何正确处理它:-(

您看到更好的方法了吗? 如何使用存根或模拟对象执行此操作?

我开始练习一个假设,即单元测试应该测试与外部因素隔离的模型/功能。 因此,我决定取消模型固有的外部行为。 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM