user10346789
user10346789

Reputation:

ActiveRecord::RecordNotFound rspec how to test

I have same problem. I don't know how to test an invalid record in this case. Help me please someone.

Need to look on: subject with wrong sms_campaign_id and in "it"

error.log

ActiveRecord::RecordNotFound: Couldn't find SmsCampaign with 'id'=12314151 [WHERE sms_campaigns.company_id = 66 AND sms_campaigns.company_id = ?]

messages_controller_spec.rb

describe PrivateApi::Company::SmsCampaigns::MessagesController do
  let(:company) { create :company, :completed, :with_superuser }
  let(:sms_campaign) { create :sms_campaign, company: company }

  describe 'GET index' do
    let(:user) { create(:user, company: company) }
    before(:each) { signin user }

    context 'when user logged with invalid sms_campaign_id' do
    subject(:index_action_invalid) { get :index, sms_campaign_id: 12314151 }

    it 'The wrong sms_campaingn_id' do
      index_action_invalid
      expect(response).to have_http_status(200)
      expect(response.content_type).to eq(Mime::JSON)
    end
  end
 end
end

messages_controller.rb

# frozen_string_literal: true

module PrivateApi
  module Company
    module SmsCampaigns
      # Resource controller to fetch all the additional messages of given SMS campaign
      class MessagesController < ::PrivateApi::Company::BaseController
        def index
          sms_campaign = SmsCampaign.where(company: @company).
            accessible_by(current_ability, :read).find(params[:sms_campaign_id])
          messages = sms_campaign.messages.order(send_at: :desc)

          render json: messages
        end
      end
    end
  end
end

Upvotes: 1

Views: 1923

Answers (1)

Stefan Rendevski
Stefan Rendevski

Reputation: 301

Assuming you are not rescuing ActiveRecord::RecordNotFound from somewhere in your controller(s), then this code will raise the error, and return a status code 404.

If you are trying to test that the exception will be raised, you need to use the matcher expect { <block_of_code> }.to raise_error <error_class>

If an exception should not be raised, then check your exception handler, because it is not being invoked.

If you want to do this without raising an ActiveRecord::RecordNotFound, you will need to switch find(id) with where(id: id).first

Upvotes: 2

Related Questions