迷你测试/摩卡:测试值是否多次更改



假设我有一个这样的服务类:

class FooService
def self.execute(foo_id)
Foo.find(foo_id).tap do |foo|
foo.update_attribute :status, :working
do_work(foo)
foo.update_attribute :status, :done
end
end
end

在 Minitest 中使用 Mocha 对此方法进行简单测试:

test 'executing the service' do
@foo = Foo.first
FooService.expects(:do_work).with(@foo)
FooService.execute(@foo.id)
assert_equal :done, @foo.reload.status
end

测试status属性是否设置为:working的最佳方法是什么?

我尝试使用Foo.any_instance.expects(:update_attribute).with(:status, :working)但由于无法在 Mocha 中调用原始实现,这会产生不良副作用。

一种解决方案是让do_work引发错误。这应该在例程结束之前停止该过程,并使foo处于状态working

FooService.expects(:do_work).raises(Exception, 'foo')
assert_equal :working, @foo.reload.status

最新更新