我對我的ArticlesController
運行以下測試。當存在有效記錄時,有效記錄`find`返回nil
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
所以find_by(id: params[:id]
找到記錄很好,但find(params[:id])
只返回零。另外find(params[:id].to_i)
返回零。任何人都可以發現原因任何幫助表示讚賞。由於
更新
的銷燬方法本身工作正常發展。這只是測試與多數民衆贊成失敗:
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)>'
'ArticlesController'中的'article'是什麼?似乎沒有定義給我。 –
@AlexanderMorozov:更新了問題。對不起,忘了補充一點,「文章」是我的控制器中的一種方法。 – JonSayer