2016-12-19 1 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)은 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 : 질문이 업데이트되었습니다. 미안 '기사'내 컨트롤러에있는 방법입니다 추가하는 것을 잊어 버렸습니다. – 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

답변 해 주셔서 감사합니다. 이것은 상당히 새로운 프로젝트이므로 atm 내 Article Model은 비어 있습니다. 이상이 없으며 오류가 아닌 것으로 판명되었습니다. – JonSayer

+0

네, 결과가 반환되지 않을 때 항상 예외를 발생시키기 때문에'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- 기록이 없을 때 –

관련 문제