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

newアクションに関連する例を実行すると、次のエラーが発生します (@article.new_record?コントローラー ファイルのコード行に関連しています)。

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

しかし、showアクションに関連する例を実行すると、エラーなしで合格します。

何が問題ですか?どうすれば解決できますか?

4

2 に答える 2

2

問題はあなたのやり方です

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

これは

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

したがって、戻り値を設定するまでには、Article.newすでにモックアウトされているため nil が返されるため、and_return(nil)最初に戻り値を作成します。つまり、

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)
于 2012-05-11T08:47:30.110 に答える
1

試す:

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

  get :new

  assigns(:article).should == article
end
于 2012-05-11T08:45:43.573 に答える