Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created August 5, 2014 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeredpath/cae3033ef0c754937b69 to your computer and use it in GitHub Desktop.
Save lukeredpath/cae3033ef0c754937b69 to your computer and use it in GitHub Desktop.
Rspec mock argument capture
# just an example of what it could be
argument = capture('label')
widget = double
# argument acts like an argument matcher that always matches but stores a reference to the real value
allow(widget).to receive(:do_something).with(argument)
# contrived, I know this could be done using the instance_of argument matcher
expect(argument.value).to be_instance_of(Something)
@myronmarston
Copy link

You can already do this:

argument = nil
allow(widget).to receive(:do_something) { |arg| argument = arg }
widget.do_something(Something.new)
expect(argument).to be_instance_of(Something)

It's unclear to me what's better about capture then the flexibility you already get from being able to pass a block?

@lukeredpath
Copy link
Author

@myronmarston nope, that's all thats needed, I wasn't aware you could yield the argument.

Copy link

ghost commented Oct 27, 2016

Still, I like the capture syntax :)

@gbirchmeier
Copy link

expect(foo).to receive(:publish_doc) do |doc|
  expect(doc.category).to eq "Code red"
  expect(doc.message).to eq "The monkeys have escaped"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment