1
votes

I'm reading up on rspec-mocks and got a little confused with Message Expectations.

A message expectation is an expectation that the test double will receive a message some time before the example ends. If the message is received, the expectation is satisfied. If not, the example fails.

validator = double("validator")
validator.should_receive(:validate).with("02134")
zipcode = Zipcode.new("02134", validator)
zipcode.valid?

So my understanding is you create a dummy object and specify it should "receive" a message (which is this validate from ActiveModel) with argument 02134. If it did at some point then this test will pass.

My question is:

  1. Why can you pass validator to Zipcode.new? Is your application code supposed to expect to take in an extra argument (test double)?

  2. What does "receive a message" mean exactly for a test double? Does it mean it will be called by the message (in this case the validate method)?

Thanks!

1

1 Answers

2
votes

There are no types in Ruby so yo can send any object to any method. This answers your 1

For your 2:

Doubles are great because to test an isolated method, you actually don't need a full object.

should_receive(:foo) means:

  • you expect your double to receive the foo method (your_double.foo somewhere)

  • foo will not be called, but it can return the result you want (use and_return) to proceed with your specs.