gpt4 book ai didi

ruby - 为什么我的测试替身不期待我允许的命令?

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:27 27 4
gpt4 key购买 nike

我有一些代码可以对 Linux 操作系统进行 shellout 调用,这将运行特定于发行版的命令。我试图确保测试可以在任何系统上运行,所以我为 Mixlib::ShellOut 调用使用了一个测试替身。这是复制我的问题的简化版本:

require 'mixlib/shellout'
class SelinuxCommand
def run
runner = Mixlib::ShellOut.new('getenforce')
runner.run_command
end
end

我的测试 stub Mixlib:ShellOut.new 返回一个测试替身,然后说 :run_command 应该返回字符串 '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

但是,当我运行测试时,我看到:

$ 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 <top (required)>'

Finished in 0.00197 seconds 1 example, 1 failure

Failed examples:

rspec ./selinuxcommand_spec.rb:5 # SelinuxCommand gets the Selinux enforcing level

我不明白为什么当我明确设置它时,double 不期望 :run_command 。我错过了什么?

最佳答案

只是因为每次调用double得到的对象都不一样,所以允许接收run_command方法的对象和stubbed返回的对象不是同一个对象。您可以这样修复它:

it 'Gets the Selinux enforcing level' do
runner = double
Mixlib::ShellOut.stub(:new).and_return(runner)

expect(runner).to receive(:run_command).and_return('Enforcing')
expect(subject.run).to eq('Enforcing')
end

关于ruby - 为什么我的测试替身不期待我允许的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21645464/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com