当有效记录存在时,Active Record`find`返回nil

时间:2016-12-19 09:38:45

标签: ruby-on-rails ruby activerecord

我正在为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;
&#13;
&#13;

所以find_by(id: params[:id]找到记录正常,但find(params[:id])只返回nil。此外find(params[:id].to_i)返回nil。谁能发现原因?任何帮助表示赞赏。感谢

更新

destroy方法本身在开发过程中按预期工作。这只是失败的测试:

&#13;
&#13;
 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;
&#13;
&#13;

2 个答案:

答案 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])有效。