Search code examples
ruby-on-railsruby-on-rails-4rspecrspec-rails

How to write rspec for exception in rails?


I have one interactor that needs to be tested for exception but i am not able to pass the spec

Interactor Body

module RecordSchedules
  class UpdateRecords
    include PureInteractor

    attr_accessor :records

    def call(records:)
      records.each do |record|
        raise StandardError, 'record cannot be processed' if record.fail
      end
      records.update_attributes(units: 0)
    end
  end
end

Rspec

require 'rails_helper'

module RecordSchedules
  RSpec.describe UpdateRecords do

    before(:all) do
      # creation of record via factory.bot
    end


    context 'record should not saved' do
      it 'throw error when record is failed' do
        expect(described_class.call(records: @record)).to raise_error('record cannot be processed')
      end
    end
  end
end

Getting failure Failure/Error: raise StandardError, 'record cannot be processed' if record.fail on executing rspec

I am not able to judge what needs to be done Thanks in advance


Solution

  • Use a block for your expectation:

    expect{
      described_class.call(records: @record)
    }.to raise_error('record cannot be processed')