2012-05-11 4 views
0

Ruby on Rails 3.2.2, Rspec 2.9.0 및 RspecRails 2.9.0을 사용하고 있습니다. new 컨트롤러 동작을 테스트하려고하는데 왜 그 동작에 대해서만 위에 설명 된 오류가 발생하는지 알고 싶습니다.'새'컨트롤러 동작을 테스트하는 방법은 무엇입니까?

을 감안할 때 :

# controller 
class ArticlesController < ApplicationController 
    before_filter :signed_in 

    def new 
    @article = Article.new 

    # This is just a sample code line to show you where the error happens? 
    @article.new_record? 

    ... 
    end 

    def show 
    @article = Article.find(params[:id]) 

    ... 
    end 
end 

# spec file 
require 'spec_helper' 

describe ArticlesController do 
    before(:each) do 
    @current_user = FactoryGirl.create(:user) 

    # Signs in user so to pass the 'before_filter' 
    cookies.signed[:current_user_id] = {:value => [@current_user.id, ...]} 
    end 

    it "article should be new" do 
    article = Article.should_receive(:new).and_return(Article.new) 
    get :new 
    assigns[:article].should eq(article) 
    end 

    it "article should be shown" do 
    article = FactoryGirl.create(:article) 

    get :show, :id => article.id.to_s 

    assigns[:article].should eq(article) 
    end 
end 

나는이 오류 (이 컨트롤러 파일의 @article.new_record? 코드 라인에 관련) 얻을 new 행동에 관한 예 실행하면 :

Failure/Error: get :new 
NoMethodError: 
    undefined method `new_record?' for nil:NilClass 

을하지만, show 동작과 관련된 예제를 실행하면 오류없이 전달됩니다.

무엇이 문제입니까? 어떻게 해결할 수 있습니까?

답변

2

문제가 반환 값, Article.new은 이미 조롱되었으므로 nil을 반환하므로 수행 중입니다 and_return(nil) ret 만들기 urn 값 먼저, 즉

new_article = Article.new #or any other way of creating an article - it may also be appropriate to return a mock 
Article.should_receive(:new).and_return(new_article) 
1

봅니다 :이 그래서 시간이 최대 설정하는

temp = Article.should_receive(:new) 
temp.and_return(Article.new) 

같은 당신이

Article.should_receive(:new).and_return(Article.new) 

를 수행 한 방법입니다

it "article should be new" do 
    article = FactoryGirl.build(:article) 
    Article.stub(:new).and_return(article) 

    get :new 

    assigns(:article).should == article 
end 
관련 문제