RSpec失败:nil的未定义方法`name':NilClass

时间:2014-04-24 11:33:13

标签: ruby-on-rails rspec

我正在阅读一本书(Action v14 MEAP中的Rails 4)并在运行我的规范时遇到错误:

Failures:

  1) Creating Projects can create a project
     Failure/Error: click_button 'Create Project'
     ActionView::Template::Error:
       undefined method `name' for nil:NilClass
     # ./app/views/projects/show.html.erb:1:in `_app_views_projects_show_html_erb__1338549725163946383_70209940313300'
     # ./spec/features/creating_projects_spec.rb:11:in `block (2 levels) in <top (required)>'

Finished in 0.23155 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/features/creating_projects_spec.rb:4 # Creating Projects can create a project

我一直在线搜索并通过书籍按照说明进行操作。我似乎无法找到我的错误。这本书(我目前在第91页)我说我应该收到以下错误:

Failure/Error: expect(page).to have_content('Project has been created.')
  expected there to be text "Project has been created." in "TextMate 2"

我对该项目的回购是http://github.com/freqn/ticketee

非常感谢任何指导。

1 个答案:

答案 0 :(得分:1)

在控制器的show方法中,设置实例变量@projects(复数)

def show
  @projects = Project.find(params[:id])
end

show视图中,您使用实例变量@project(单数)。

<h2><%= @project.name %></h2>

因此,没有实例变量@project,因此当视图尝试调用name方法时,它实际上正在执行nil.name,因此{ {1}}错误。

更改您的控制器方法:

undefined method