我有同样的问题。在这种情况下,我不知道如何测试无效的记录。请帮我一个人。
需要关注:带有错误sms_campaign_id且位于“ it”中的主题
ActiveRecord :: RecordNotFound:找不到'id'= 12314151 [WHERE sms_campaigns
。company_id
= 66 AND sms_campaigns
。company_id
=?]的SmsCampaign。 / p>
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
# 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
答案 0 :(得分:1)
假设您没有从控制器中的某处营救ActiveRecord::RecordNotFound
,则此代码将引发错误,并返回状态代码404
。
如果您要测试是否会引发异常,则需要使用匹配器expect { <block_of_code> }.to raise_error <error_class>
如果不应引发异常,请检查异常处理程序,因为它没有被调用。
如果您想在不提高ActiveRecord::RecordNotFound
的情况下执行此操作,则需要将find(id)
切换为where(id: id).first