rspec错误:通过示例学习Rails:当你没有想到它时,你有一个nil对象

时间:2011-12-09 01:11:35

标签: ruby-on-rails rspec

在Mike Hartl通过示例教程学习Rails时,我收到了一个奇怪的rspec错误。

在页419,代码清单10.30:代码如下:

it "should have an element for each user" do
get :index
@users[0..2].each do |user|
response.should have_selector("li", :content => user.name)
end
end

当我运行rspec时,我收到此错误消息。:

故障:

1) UsersController GET 'index' for signed-in-users should have an element for each user
    Failure/Error: @users[0..2].each do |user|
    NoMethodError:
      You have a nil object when you didn't expect it!
      You might have expected an instance of Array.
      The error occurred while evaluating nil.[]
    # ./spec/controllers/users_controller_spec.rb:40

Finished in 2.58 seconds 75 examples, 1 failure

Failed examples:

rspec ./spec/controllers/users_controller_spec.rb:38 # UsersController GET 'index' for >signed-in-users should have an element for each user

我做了一些研究并在这个帖子中发现了类似的问题,但我仍然无法通过测试。

有什么想法吗?

参考链接:

Why are my RSpec tests failing, but my app is working?

Cookies do not persist in Rspec on rails 3.1

Rails Tutorial chapter 10.3.3 - 4 RSpec Errors (app working)

2 个答案:

答案 0 :(得分:0)

似乎没有在测试数据库中创建用户。通过插入

检查@users中有多个用户
puts @users.length

获取后:'

如果这是零,你应该仔细检查你的前一块。

答案 1 :(得分:0)

我只是想通了。

@users[0..2].each do |user|

需要成为:

User.paginate(:page => 1).each do |user|

该应用程序仍适用于任何一行,但要通过rspec测试,您需要使用User.paginate。