Search code examples
rubyrspecstripe-paymentsrspec-railsruby-on-rails-6

How to do conditional rspec code based on tags


Is there a way add an if statement around:

  invalid_customer = RuntimeError.new("error code")
  StripeMock.prepare_error(invalid_customer, :create_source)

based on if the live_only or live tag is not called?

I would live to eliminate the live and mock tests and only have one since it's redundant.

Result

rspec spec --tag live_only => would not run the above StripeMock code
rspec spec => would run the mock code

Rspec

it "should raise error when invalid customer (Live Version)", live_only: true do
  err = "error code"
  expect {
    payment_gateway.add_source(customer_id: "invalid-id", source_id_or_token: default_card_token)
  }.to raise_error(RuntimeError) {|e|
    expect(e.message).to eql err
  }
end

it "should raise error when invalid customer (Mock Version)", live: false do
  invalid_customer = RuntimeError.new("error code")
  StripeMock.prepare_error(invalid_customer, :create_source)
  
  expect {
    payment_gateway.add_source(customer_id: "invalid-id", source_id_or_token: default_card_token)
  }.to raise_error(RuntimeError) {|e|
    expect(e.message).to eql "error code"
  }
end

Updated

I found a way to set a variable @running_mock, see answer below..


Solution

  • I found a way to set a variable @running_mock.

      config.before(:example) do
        @running_mock ||= (config.filter_manager.inclusions.rules.to_hash.keys & [:live,:live_only]).blank?
      end
    

    RSpec

    it "should raise error when invalid customer (Live & Mock Version)", live: true do
      if @running_mock
        invalid_customer = RuntimeError.new("error code")
        StripeMock.prepare_error(invalid_customer, :create_source)
      end
    
      expect {
        payment_gateway.add_source(customer_id: "invalid-id", source_id_or_token: default_card_token)
      }.to raise_error(RuntimeError) {|e|
        expect(e.message).to eql "error code"
      }
    end