2016-12-19 114 views
0

我對我的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)>'

+0

'ArticlesController'中的'article'是什麼?似乎沒有定義給我。 –

+0

@AlexanderMorozov:更新了問題。對不起,忘了補充一點,「文章」是我的控制器中的一種方法。 – JonSayer

回答

0

所以我找到了答案。問題出在我測試中的鏈接:expect(Article).to receive(:find).with(article.id.to_s)。沒有說明我想要Article.find(params[:id)返回,它返回nil。因此沒有收到錯誤消息,並且`find_by(id:params [:id])有效。

0

其實find提高RecordNotFound異常,當找不到記錄,這樣就不能簡單地把nil並繼續執行你的功能,請確保您在Article模型中不會覆蓋您的查找功能。

+0

感謝您的回答。這是一個相當新的項目,所以我的文章模型是空的。奇怪的是,沒有返回,而不是一個錯誤。 – JonSayer

+0

是的,當然這就是爲什麼'find'和'find_by_id'或者你的'find_by(id:value)'作爲'find'總是會在沒有結果返回時引發異常。 也檢查http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find 並檢查此答案也http://stackoverflow.com/questions/9604585/find-with-nil-當-那裏 - 是 - 無記錄 –