Verify a Ruby Class Method is Called with Arguments in Rspec, Without Doubles or Mocks
While working on Testing Chef's ruby_block
s with ChefSpec, I found that I was struggling to find any resources explaining my seemingly niche request:
- testing a ruby block calls a class (static) method
- verifying that the correct arguments are passed to it
- while preserving original implementation - therefore ruling out using doubles or mocks
As this didn't seem to dig up much (perhaps due to using the wrong words for names) I ended up being able to bruteforce a solution using Rspec's expected
syntax:
# impl
def function(arg)
...
val = Chef::Recipe::RubyBlockHelper.run_state_public_key(arg1, arg2, arg3)
...
end
# spec
it '...' do
# given
expect(Chef::Recipe::RubyBlockHelper).to receive(:run_state_public_key)
.with('hello', 'www-spectatdesigns-co-uk', 'blah_blah_key')
.and_call_original
# when
out = other_object.function('arg')
# then
expect(out).to ...
end
A couple of points to note:
- by using an
expect
here, instead of anallow
, Rspec will raise an error ifrun_state_public_key
isn't received .and_call_original
ensures we will preserve original functionality ofrun_state_public_key