2016-12-19 5 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])はnilを返します。また find(params[:id].to_i)はnilを返します。なぜ誰にスポットを付けることができますかどんな助けもありがとうございます。おかげ

は開発中の期待通りにdestroyメソッド自体が機能

を更新しました。これで失敗thatsの単なるテストです:それは単にnilを置き、あなたの関数の実行を継続することはできませんので

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:質問を更新しました。申し訳ありませんが、 'article'が私のコントローラのメソッドであることを追加するのを忘れました。 – 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例外レコードを見つけることができないとき、あなたのことを確認してくださいArticleモデルの検索機能を上書きしません。

+0

あなたの答えをありがとう。これはかなり新しいプロジェクトですので、私の記事モデルは空です。それは奇数が返されていてエラーではないことが奇妙であることが分かった。 – JonSayer

+0

はい、確かに 'find'が返された結果がないときに例外を発生させるので、' find'と 'find_by_id'または' find_by(id:value) 'があるのは確かです。 http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find もチェックし、この回答も確認してください。http://stackoverflow.com/questions/9604585/find-with-nil-レコードがないとき –

関連する問題