我正在学习 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 对象,但理论上在单元测试中我不应该依赖外部因素。我认为“存根”、“模拟”等,但看不到如何正确处理:-(
你有没有更好的方法来做到这一点?我怎么能使用存根或模拟对象来做到这一点?