Minitest / Mocha:测试值是否多次更改

时间:2018-09-29 19:04:59

标签: ruby mocha minitest

假设我有这样的服务类:

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

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

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中调用原始实现,因此副作用很严重。

1 个答案:

答案 0 :(得分:0)

一种解决方案是获取do_work来引发错误。那应该在例程结束之前停止该过程,并使foo的状态为working

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