【问题标题】:How to write a RSpec test to compare a string with its expected substring?如何编写 RSpec 测试以将字符串与其预期的子字符串进行比较?
【发布时间】:2015-10-04 17:28:25
【问题描述】:

我有一个这样的 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/ 部分的子字符串。

我的预期消息应该是“来自文件 MySampleEnvironment.json --config 'knife.rb' 的刀环境”

这应该与从knife.chef_cmd_to_s 方法返回的实际消息匹配: "C:/blah/blah/bin/knife 环境来自文件 MySampleEnvironment.json --config 'knife.rb'"

我该怎么做?为此使用什么 Rspec 匹配器?

【问题讨论】:

    标签: ruby rspec rspec2


    【解决方案1】:

    这是您将使用 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
    

    【讨论】:

    • 这正是我想要的。谢谢。由于声誉低,无法为您的答案投票。
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多