如何编写 RSpec 测试来将字符串与其预期的子字符串进行比较?
How to write a RSpec test to compare a string with its expected substring?
我有一个这样的 RSpec 测试:
context 'test #EnvironmentFile= method' do
it 'compares the command generated with the expected command' do
knife = EnvironmentFromFile.new(@knife_cfg_file)
knife.environment_file=(@environment_file)
expect(knife.chef_cmd_to_s).to eql("C:/blah/blah/bin/knife environment from file MySampleEnvironment.json --config 'knife.rb'")
end
end
现在,为了避免平台依赖性,eql() 中的预期消息应该是没有初始 C:/blah/blah/bin/ 部分的子字符串。
我预期的消息应该是 "knife environment from file MySampleEnvironment.json --config 'knife.rb'"
这应该与从 knife.chef_cmd_to_s 方法返回的实际消息相匹配:
"C:/blah/blah/bin/knife environment from file MySampleEnvironment.json --config 'knife.rb'"
我该怎么做?什么 Rspec 匹配器用于此?
这是您要使用 include
匹配器 (documentation) 的地方。
context 'test #EnvironmentFile= method' do
it 'compares the command generated with the expected command' do
knife = EnvironmentFromFile.new(@knife_cfg_file)
knife.environment_file=(@environment_file)
expect(knife.chef_cmd_to_s).to include("knife environment from file MySampleEnvironment.json --config 'knife.rb'")
end
end
我有一个这样的 RSpec 测试:
context 'test #EnvironmentFile= method' do
it 'compares the command generated with the expected command' do
knife = EnvironmentFromFile.new(@knife_cfg_file)
knife.environment_file=(@environment_file)
expect(knife.chef_cmd_to_s).to eql("C:/blah/blah/bin/knife environment from file MySampleEnvironment.json --config 'knife.rb'")
end
end
现在,为了避免平台依赖性,eql() 中的预期消息应该是没有初始 C:/blah/blah/bin/ 部分的子字符串。
我预期的消息应该是 "knife environment from file MySampleEnvironment.json --config 'knife.rb'"
这应该与从 knife.chef_cmd_to_s 方法返回的实际消息相匹配: "C:/blah/blah/bin/knife environment from file MySampleEnvironment.json --config 'knife.rb'"
我该怎么做?什么 Rspec 匹配器用于此?
这是您要使用 include
匹配器 (documentation) 的地方。
context 'test #EnvironmentFile= method' do
it 'compares the command generated with the expected command' do
knife = EnvironmentFromFile.new(@knife_cfg_file)
knife.environment_file=(@environment_file)
expect(knife.chef_cmd_to_s).to include("knife environment from file MySampleEnvironment.json --config 'knife.rb'")
end
end