Verify a Ruby Class Method is Called with Arguments in Rspec, Without Doubles or Mocks

While working on Testing Chef’s ruby_blocks with ChefSpec, I found that I was struggling to find any resources explaining my seemingly niche request:

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:

*****

Written by Jamie Tanna on 07 March 2018, and last updated on 30 April 2018.

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under Apache License 2.0.

Tags

Categories