Bryan Perez
Bryan Perez

Reputation: 61

How to assert in MiniTest if method is sent to object that is NOT a mock?

I understand that we can check if methods are sent to Mock objects using expect, but what about checking if methods are sent to objects that aren't Mocks, but actual objects in your app?

Motivation: Sandi Metz' talk 'Magic Tricks of Testing' https://www.youtube.com/watch?v=URSWYvyc42M says that for unit testing outgoing command method calls (explained in her talk), we should verify that the message is sent. I'm attempting to do so but the only thing I've found in MiniTest is assert_send, which has a few issues:

  1. It's deprecated.
  2. It doesn't take into account the value of the arguments sent to the receiving object. If I run assert_send([object, :method_called, 'argument 1', 'argument 2']), the assertion will return true, even if object was expecting different strings than 'argument 1' and 'argument 2'.

I've scoured the internet for the better part of 2 days on this. Anyone have any ideas?

Upvotes: 1

Views: 2522

Answers (1)

Bryan Perez
Bryan Perez

Reputation: 61

Figured out the answer to my own question :)

Posting this in case anyone else had trouble like me.

Using the Spy gem you can assert a method has been called.

From this post by Ilija Eftimov - https://ieftimov.com/test-doubles-theory-minitest-rspec

class BlogTest < Minitest::Test
  def test_notification_is_sent_when_publishing
    notification_service_spy = Spy.on(NotificationService, :notify_subscribers)
    post = Post.new
    user = User.new
    blog = Blog.new(user)

    blog.publish!(post)

    assert notificaion_service_spy.has_been_called?
  end
end

Upvotes: 1

Related Questions