【发布时间】:2026-01-12 02:30:01
【问题描述】:
我有一个更新人物属性的方法,如果找不到人物,它会拯救ActiveRecord::RecordNotFound。方法是:
def update
@people= People.find(params[:id])
if @people.update(people_params)
render json: { success: 'Success' }
else
render :edit
end
rescue ActiveRecord::RecordNotFound => e
render json: { error: 'Failed') }
end
我想测试一下没有找到记录的情况,下面是我的测试:
let(:people) { create(:people) }
let(:people_id) { people.id }
let(:user) { people}
# Other tests...
context 'when person not found' do
let(:exception) { ActiveRecord::RecordNotFound }
# What should I write so that I can let the record not been found?
before { allow(People).to receive(:find).and_raise(exception) }
it 'responds with json containing the error message' do
expect(JSON.parse(response.body)).to eq({error:'Error'})
end
end
我希望在未找到记录的情况下执行我的测试。但我不知道该怎么做。我试图设置let(people) {nil},但它不起作用。有没有办法做到这一点?谢谢!
【问题讨论】:
-
为什么您的测试不起作用?我觉得很好
-
不是错字吗?你的班级是
People,而不是Person。 -
你也错过了这个请求,或者你在一些bedore/let中做它?
-
谢谢大家,我刚刚找到了解决办法,导致找不到记录的方法是把人的id改成un-exit的。
-
由于 DRY 原则,通常您不需要在控制器中挽救
RecordNotFound错误。您可以在父控制器中定义它
标签: ruby-on-rails ruby unit-testing rspec