首页 > 解决方案 > Minitest/Mocha:测试一个值是否多次变化

问题描述

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

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 with 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 中调用原始实现,因此会产生不好的副作用。

标签: rubyminitestruby-mocha

解决方案


一种解决方案是do_work引发错误。那应该在例程结束之前停止该过程并foo保持状态working

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

推荐阅读