我正在使用 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
它会毫无错误地通过。
问题是什么?我该如何解决?