Filip Bartuzi
Filip Bartuzi

Reputation: 5931

Test parameter vs multiple regexp n RSpec

I have a method which handle failure on some api calls. I wrote tests for it:

  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

but to make it work I would need to make 3 api calls or split it to 3 test cases. I don't like both of the solutions. I think the best one would be to combine 3 regexp into single expectation.

Is it possible to put multiple Regexps on single parameter in one test case?

Upvotes: 1

Views: 104

Answers (1)

Filip Bartuzi
Filip Bartuzi

Reputation: 5931

You could combine all these regexp into one (using regexp's AND operator).

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

this regexp will test string if it matches all of above.

Then inside a test case:

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

Upvotes: 1

Related Questions