Bogatyr
Bogatyr

Reputation: 19323

Rails / Rspec: .should_receive(method).with(parameter) where parameter is not known until tested method is called

I have a method that creates a new object and calls a service with that new object as a parameter, and returns the new object. I want to test in rspec that the method calls the service with the created object, but I don't know the created object ahead of time. Should I also stub the object creation?

def method_to_test
   obj = Thing.new
   SomeService.some_thing(obj)
end

I'd like to write:

SomeService.stub(:some_thing)
SomeService.should_receive(:some_thing).with(obj)
method_to_test

but I can't because I don't know obj until method_to_test returns...

Upvotes: 0

Views: 139

Answers (1)

apneadiving
apneadiving

Reputation: 115531

Depending whether or not it's important to checkobj you can do:

SomeService.should_receive(:some_thing).with(an_instance_of(Thing))
method_to_test

or:

thing = double "thing"
Thing.should_receive(:new).and_return thing
SomeService.should_receive(:some_thing).with(thing)
method_to_test

Upvotes: 3

Related Questions