rspec yield block, but call original
Asked Answered
S

2

12

So I have the following:

foo.each do |f|
  f.begin
    do_stuff
    do_more_stuff
  end
end

And I mock the f object with an and_yield() call. I want to be able to test the begin method by passing it the original block { do_stuff do_more_stuff }, not a mock implementation.... I cant just let the begin method be called on the mock without at least stubbing it, so what do I do?

Soldierly answered 14/10, 2014 at 17:33 Comment(0)
S
20

Again, an undocumented feature that i found:

allow(thing).to receive(:foo) do |_, &block|
  block.call
end

le sigh....

Soldierly answered 14/10, 2014 at 20:59 Comment(3)
Not undocumented: relishapp.com/rspec/rspec-mocks/v/3-1/docs/…Uncritical
Awesomesauce! I guess I am just blindSoldierly
With RSpec 3.10.x, I had luck with and_wrap_original. rspec.info/documentation/3.3/rspec-mocks/RSpec/Mocks/…Flatiron
D
5

The following worked for me:

original = thing.method(:foo)
expect(thing).to receive(:foo) do |_params|
  # check params
  expect(params).to include(something)

  # then
  original.call(params)
end
Donation answered 15/11, 2021 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.