2010-09-27 23 views
2

我有以下规格的spec/views/users/new.html.erb_spec.rb无法获得RSpec的视图规范通过

require 'spec_helper' 

describe "users/new.html.erb" do 
    it "displays the text attribute of the message" do 
    render 
    response.should contain("Register") 
    end 
end 

但是当我运行测试失败:

ActionView::TemplateError in 'users/new.html.erb displays the text attribute of the message' 
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

线是失败的是:

<% form_for @user, :url => account_path do |f| %> 

在我Users控制器为new方法,我有这样的:

@user = User.new 

任何想法,为什么我得到那个错误?

更新:根据要求,这里是我的路线文件...

ActionController::Routing::Routes.draw do |map| 
    map.resource :account, :controller => "users" 
    map.resources :users 

    map.connect ':controller/:action/:id' 
    map.connect ':controller/:action/:id.:format' 
end 
+0

你可以发布你的路由文件? – 2010-09-27 17:47:45

+0

发布路由更新 – Shpigford 2010-09-27 17:55:34

回答

3

视图的定义是从用户控制器完全隔离运行。因此,您必须自己初始化视图中所需的变量,如here所述。结果会是这样的:

require 'spec_helper' 
require 'path/to/user.rb' 

describe "users/new.html.erb" do 
    it "displays the text attribute of the message" do 
    assigns[:user] = User.new 
    render 
    response.should contain("Register") 
    end 
end 

如果你想与你的控制器一起测试你的视图,我会建议寻找与黄瓜的集成测试。

+3

在RSpec 2.8中,不赞成使用'response'。改用'rendered'代替。 – evanrmurphy 2012-03-14 15:42:37

1

只是一个更新的答案。

require 'spec_helper' 

describe "users/new.html.erb" do 
    it "displays the text attribute of the message" do 
    assign(:user, stub_model(User)) 
    render 
    expect(rendered).to include("Register") 
    end 
end 

这应该在轨道上运行3.2.13和RSpec 2.13.0