RSpec Arbitrary Handling of Arguments


Filed under: rspec, tdd

RSpec lets you test the number, type, and order of arguments. For example,

Foo.should_receive(:bar).with(1, kind_of(Hash), anything()), {'a' => 'b'}, &b)


This tests that class method bar will be called against class Foo with 3 arguments. The first argument is integer 1, the second argument is an instance of Hash, the third argument can be anything.

What if you want to test a bit more on the argument than that?

For example, in order to test a private_pub method publish_to:

PrivatePub.should_receive(:publish_to) do |channel, data|
  channel.should eq 'messages/new'
  data[:foo].should eq 'foo'
PrivatePub.publish_to['messages/new', {:foo => 'foo'}


This tests that publish_to takes 2 arguments. The first is channel and should be equal to ‘messages/new’. The second is a hash and it equals to {:foo => ‘foo’}