Why is my test double not expecting the command I allowed?-Collection of common programming errors
I have some code which makes shellout calls to the Linux OS, which will run distro-specific commands. I’m trying to ensure the tests can be run on any system, so am using a test double for the Mixlib::ShellOut
call. Here’s a simplified version that replicates my issue:
require 'mixlib/shellout'
class SelinuxCommand
def run
runner = Mixlib::ShellOut.new('getenforce')
runner.run_command
end
end
My test stubs Mixlib:ShellOut.new
returning a test double, and then says that :run_command
should return the string 'Enforcing'
:
require 'rspec'
require_relative 'selinuxcommand'
describe SelinuxCommand do
it 'gets the Selinux enforcing level' do
command = SelinuxCommand.new
Mixlib::ShellOut.stub(:new).and_return(double)
allow(double).to receive(:run_command).and_return('Enforcing')
expect command.run.to eql 'Enforcing'
end
end
However, when I run the test I see:
$ rspec -fd selinuxcommand_spec.rb
SelinuxCommand gets the Selinux enforcing level (FAILED - 1)
Failures:
1) SelinuxCommand gets the Selinux enforcing level
Failure/Error: expect command.run.to eql 'Enforcing'
Double received unexpected message :run_command with (no args)
# ./selinuxcommand.rb:5:in `run'
# ./selinuxcommand_spec.rb:9:in `block (2 levels) in '
Finished in 0.00197 seconds 1 example, 1 failure
Failed examples:
rspec ./selinuxcommand_spec.rb:5 # SelinuxCommand gets the Selinux enforcing level
I don’t understand why the double doesn’t expect :run_command
when I explicitly set it up to expect that. What have I missed?