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:

  • 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 an allow, Rspec will raise an error if run_state_public_key isn't received
  • .and_call_original ensures we will preserve original functionality of run_state_public_key

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

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 the Apache License 2.0.

Tags
Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.