0

Let's say I have a service class as such:

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

A simple test for this method in 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

What would be the best way to test that the status attribute was set to :working?

I've tried using Foo.any_instance.expects(:update_attribute).with(:status, :working) but since there is no way to call the original implementation in Mocha this has bad side effects.

Vega
  • 27,856
  • 27
  • 95
  • 103
user1032752
  • 751
  • 1
  • 11
  • 28

1 Answers1

0

One solution would be to get do_work to raise an error. That should stop the process before the end of the routine and leave foo in status working

FooService.expects(:do_work).raises(Exception, 'foo')
assert_equal :working, @foo.reload.status
ReggieB
  • 8,100
  • 3
  • 38
  • 46
  • Thanks for the reply. Let's say I already have exception handling that changes the status to `:failed` and a test case similar to the above that asserts that. In theory I could use two different error classes but it just feels "wrong". – user1032752 Oct 01 '18 at 13:09