我正在为ArticlesController
运行以下测试。
describe "#destroy" do
let(:article) { articles(:article_1) }
let(:request) { delete :destroy, params: { id: article.id.to_s } }
it 'returns a 200 status socde when a correct request is made' do
request
expect(request.status).to eq 302
end
it 'deletes an article' do
expect{ request }.to change{ Article.count }.by(-1)
end
it 'deletes the correct article' do
expect(Article).to receive(:find).with(article.id.to_s)
request
end
end

这是我在ArticlesController
中的当前销毁行动:
def destroy
p "********"
p params[:id].to_i
p Article.find_by(id: params[:id])
p Article.find(params[:id])
article.destroy
redirect_to articles_path
end
def article
@article ||= Article.find(params[:id])
end

输出(仅用于最终测试,前两次传递):
"********"
960213061
#<Article id: 960213061, title: "First Article", body: "This is the first test article", published_at: nil, created_at: "2016-12-19 09:11:55", updated_at: "2016-12-19 09:11:55">
nil
F
&#13;
所以find_by(id: params[:id]
找到记录正常,但find(params[:id])
只返回nil。此外find(params[:id].to_i)
返回nil。谁能发现原因?任何帮助表示赞赏。感谢
更新
destroy方法本身在开发过程中按预期工作。这只是失败的测试:
1) ArticlesController#destroy deletes the correct article
Failure/Error: article.destroy
NoMethodError:
undefined method `destroy' for nil:NilClass
# ./app/controllers/articles_controller.rb:30:in `destroy'
# ./spec/controllers/articles_controller_spec.rb:101:in `block (3 levels) in <top (required)>'
# ./spec/controllers/articles_controller_spec.rb:114:in `block (3 levels) in <top (required)>'
&#13;
答案 0 :(得分:0)
实际上find
如果无法找到记录就会引发RecordNotFound
异常,因此它无法简单地放置nil
并继续执行您的功能,请确保您不是覆盖Article
模型中的查找功能。
答案 1 :(得分:0)
所以我找到了答案。问题在于我的测试中的链接:expect(Article).to receive(:find).with(article.id.to_s)
。如果不说明我想要Article.find(params[:id)
返回的内容,则会返回nil
。因此没有收到错误消息,并且`find_by(id:params [:id])有效。