【问题标题】:Test parameter vs multiple regexp n RSpec测试参数与多个正则表达式 n RSpec
【发布时间】:2015-11-13 10:26:50
【问题描述】:

我有一个处理某些 api 调用失败的方法。我为它写了测试:

  it 'logs the error' do
    expect(Rails.logger).to receive(:error).with(/Failed API call/i)
    expect(Rails.logger).to receive(:error).with(/#{error_type}/)
    expect(Rails.logger).to receive(:error).with(/#{server_error}/)
    subject
  end

但要使其正常工作,我需要进行 3 个 api 调用或将其拆分为 3 个测试用例。我不喜欢这两种解决方案。我认为最好的方法是将 3 个正则表达式组合成一个期望。

是否可以在一个测试用例中将多个正则表达式放在单个参数上?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rspec shoulda


    【解决方案1】:

    您可以将所有这些正则表达式组合成一个(使用正则表达式的 AND 运算符)。

      let(:expected_log_message) do
        /(?=.*Failed API call)(?=.*#{error_type})(?=.*#{server_error})/i
      end
    

    此正则表达式将测试字符串是否匹配以上所有内容。

    然后在一个测试用例中:

      it 'logs the error' do
        expect(Rails.logger).to receive(:error).with(expected_log_message)
        subject
      end
    

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多