【问题标题】:Active Record `find` returns nil when a valid record exists当存在有效记录时,Active Record `find` 返回 nil
【发布时间】:2017-05-04 07:53:59
【问题描述】:

我正在为我的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

所以find_by(id: params[:id] 发现记录很好,但find(params[:id]) 只返回 nil。同样find(params[:id].to_i) 返回零。谁能发现为什么?任何帮助表示赞赏。谢谢

更新

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)>'

【问题讨论】:

  • article 中的ArticlesController 是什么?对我来说似乎是未定义的。
  • @AlexanderMorozov:更新了问题。抱歉忘了补充 article 是我控制器中的一个方法。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

实际上find 在找不到记录时引发RecordNotFound 异常,因此它不能简单地放置nil 并继续执行您的函数,请确保您没有在Article 模型中覆盖您的查找函数。

【讨论】:

【解决方案2】:

所以我找到了答案。问题出在我的测试中的链接:expect(Article).to receive(:find).with(article.id.to_s)。没有说明我希望 Article.find(params[:id) 返回什么,它返回 nil。因此没有收到错误消息并且 `find_by(id: params[:id]) 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多