ActiveRecord :: RecordNotFound rspec如何测试

时间:2018-11-22 09:05:19

标签: ruby-on-rails ruby rspec

我有同样的问题。在这种情况下,我不知道如何测试无效的记录。请帮我一个人。

需要关注:带有错误sms_campaign_id且位于“ it”中的主题

error.log

ActiveRecord :: RecordNotFound:找不到'id'= 12314151 [WHERE sms_campaignscompany_id = 66 AND sms_campaignscompany_id =?]的SmsCampaign。 / p>

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

1 个答案:

答案 0 :(得分:1)

假设您没有从控制器中的某处营救ActiveRecord::RecordNotFound,则此代码将引发错误,并返回状态代码404

如果您要测试是否会引发异常,则需要使用匹配器expect { <block_of_code> }.to raise_error <error_class>

如果不应引发异常,请检查异常处理程序,因为它没有被调用。

如果您想在不提高ActiveRecord::RecordNotFound的情况下执行此操作,则需要将find(id)切换为where(id: id).first