【问题标题】:How to test 'new' controller actions?如何测试“新”控制器动作?
【发布时间】:2012-05-11 08:32:33
【问题描述】:

我正在使用 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 操作相关的示例时,它会顺利通过。

有什么问题?我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec controller


    【解决方案1】:

    问题在于你的做法

    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)
    

    【讨论】:

      【解决方案2】:

      试试:

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

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2011-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多