RSpec:未定义方法`name'为零:NilClass
问题描述:
我在从railstutorial.org上看到这个错误时遇到了这个错误。RSpec:未定义方法`name'为零:NilClass
模型类:$ APPLICATION_HOME /应用/型号/ user.rb
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
#validations
validates :name, presence: true, length: { maximum: 50}
valid_email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: valid_email_regex },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
end
查看页面:$ APPLICATION_HOME /应用/视图/ show.html.erb文件
<% provide :title, @user.name %>
<h1><%= @user.name %></h1>
RSpec的文件: $ APPLICATION_HOME /应用/规格/请求/ user_pages_spec.rb
require 'spec_helper'
describe "UserPages" do
subject { page }
describe "signup page" do
before { visit signup_path }
it { should have_selector('h1', text: "Sign up") }
it { should have_selector('title', text: full_title('Sign up')) }
end
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
end
end
这里是factories.rb我已经把$ APPLICATI ON_HOME /规格/ factories.rb
FactoryGirl.define do
factory :user do
name "amit"
email "[email protected]"
password "foobar"
end
end
的Gemfile
group :test do
gem 'capybara', '1.1.2'
gem 'factory_girl_rails'
end
这里的快照是记录在测试规范中我得到。
Failures:
1) UserPages profile page
Failure/Error: before { visit user_path(user) }
ActionView::Template::Error:
undefined method `name' for nil:NilClass
# ./app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb__369651065_78543920'
# ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'
2) UserPages profile page
Failure/Error: before { visit user_path(user) }
ActionView::Template::Error:
undefined method `name' for nil:NilClass
# ./app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb__369651065_78543920'
# ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'
Finished in 0.68212 seconds
12 examples, 2 failures
的错误出现在这两条线
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
请帮我解决这些错误。
谢谢,阿米特·帕特尔
答
这是错字在$ APPLICATION_HOME /应用/控制器/ users_controller.rb
def show
@users = User.find(params[:id])
end
如果您发现,实例变量名使用复数(@users),我有在erb模板中使用单数名称(@user)。这就是它失败的原因。