Rafa de Castro
Rafa de Castro

Reputation: 2524

Checking parameters of method calls to a test double in RSpec

Is it possible to check if the parameters passed to the parameters of a method call fulfill certain constraints. I would like to do something like

my_double = double("MyObject")
my_double.should_receive(:mocked_method).with{ <something that has an attribute called name and value "john"> }

Thanks a lot in advance.

Edit: I'll try to clarify a bit what I want to accomplish

What I want is to check that a given method of a mock was called passing an object that fulfils some conditions

Upvotes: 4

Views: 4957

Answers (3)

Jan Klimo
Jan Klimo

Reputation: 4930

Just to add, if your method accepts multiple arguments, you can do the following in your block:

allow_any_instance_of(MyClass).to receive(:my_method) do |*args|
  expect(args[0]).to include "something"
  expect(args[1]).to match(/something_else/)
  # etc
end

Upvotes: 2

Rafa de Castro
Rafa de Castro

Reputation: 2524

For the record. What I wanted to accomplish can be made with

  @test_double.should_receive(:send_mail) do |mail|
    mail.to.should eq(["[email protected]"])
    mail.body.decoded.should include "Error"
  end

And the code should call the method send_mail of the given object with a parameter that fulfills the conditions specified in the block.

Upvotes: 7

ian
ian

Reputation: 12251

In my view, it should really be a seperate test:

context "after being passed to my_double" do
  before { my_double( XXX ) }
  subject { XXX }
  it { should respond_to :attribute }
  describe :attribute do
    subject { XXX.attribute }
    it { should == 5 }
  end
end

Upvotes: 0

Related Questions