ActiveRecord::RecordNotFound rspec如何测试



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

需要关注:主题sms_campaign_id错误并且在"it"中

error.log

ActiveRecord::RecordNotFound:找不到"id"=12314151[其中sms_campaigns.company_id=66 ANDsms_campaigns.company_id=?]的SmsCampaign

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

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

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

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

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

最新更新