ruby-on-rails - 无法让 RSpec View 规范通过

标签 ruby-on-rails testing rspec

我在 spec/views/users/new.html.erb_spec.rb 中有以下规范:

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| %>

new 方法的 Users Controller 中,我有以下内容:

@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

最佳答案

View 规范与用户 Controller 完全隔离运行。因此,您必须自己初始化 View 中所需的变量,如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

如果您想与 Controller 一起测试 View ,我建议您考虑使用 Cucumber 进行集成测试。

关于ruby-on-rails - 无法让 RSpec View 规范通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806049/

相关文章:

html - 如何按特定顺序放置学生 block ?

ruby-on-rails - has_and_belongs_to_many 验证,以便用户不能多次申请车间

javascript - 协助在类中 stub 函数

ruby-on-rails - Rails 3 Autotest 说 "command not found",有什么想法吗?

ruby-on-rails - 多列的相同枚举值

ruby-on-rails - 在我的 GSuite 日历上创建事件并使用服务帐户邀请与会者

go - 使用http.NewRequest进行测试时,为什么我的请求URL解析不正确?

angular - 错误 : StaticInjectorError(DynamicTestModule)[CityService -> Http]: No provider for Http

ruby-on-rails - 如何模拟 RSpec 期望语法中的类方法?

javascript - 测试 Angular/Rails 应用程序的首选方法是什么?