Search code examples
rubytestingrspectddrspec-mocks

RSpec: Mocks, Stubs and Verification


I'm writing a plugin for Cinch (the IRC bot), and trying to write some RSpec tests for it.

However, I'm trying to get to grips with RSpec, and mocking out the external dependencies of this plugin. I want to test two different things for now - that it says hello to people, and that it keeps track of who it's said hello to.

So I've got a method, say_hello, which takes a Cinch::Message. What's the easiest way to mock this particular class? I'm used to Mockito and Java, so I'm used to making a mock of a particular class.

How can I make a mock of Cinch::Message? In my first test, I want to assert that the reply method is called on that message. In the next one, I just want it to respond like a Cinch::Message would, as I only care about the tracking the class does, not the interaction with the message.

I've only just started out with RSpec, so maybe I'm missing something fundamental. Should I be using a mock? A stub?

Thanks!


Solution

  • First of all documentation would be a nice start point, see: https://www.relishapp.com/rspec/rspec-mocks/v/2-11/docs/message-expectations

    ..and this is how your test could look:

    it 'should call #reply on the message'
      message = double('cinch message')
      message.should_receive(:reply)
      object_under_test.say_hello(message)
    end