【问题标题】:Failure/Error: get :index NoMethodError: undefined method `<=' for nil:NilClass失败/错误:获取:索引 NoMethodError:未定义的方法 `<=' for nil:NilClass
【发布时间】:2015-09-15 11:01:11
【问题描述】:

我希望这不是一个特定的错误,它可能是一个逻辑错误,也可以帮助其他人。

我想测试我的控制器索引方法,并且我有一个带有活动记录查询的 before 方法。问题是我无法弄清楚我的测试出了什么问题,因为我只有在使用 rspec 而不是手动测试时才会出现此错误。

控制器

class BlogsController < ApplicationController
  before_filter :archive_months

def archive_months
@months = Blog.find(:all, :select=>:publish_date, :order=>"publish_date DESC")
                .select{ |p| p.publish_date <= Date.today }
                .group_by{ |p| [p.year, p.month, p.publish_date.strftime("%B")] }
end

测试

require 'rails_helper'

RSpec.describe BlogsController, :type => :controller do
  before(:each) do
    @post1 = create(:blog)
  end
  describe "GET #index" do

    it "shows all blog posts" do
      get :index
      expect(response).to have_http_status(200)
    end
  end
end

测试输出

1) BlogsController GET #index shows all blog posts
     Failure/Error: get :index
     NoMethodError:
       undefined method `<=' for nil:NilClass
     # ./app/controllers/blogs_controller.rb:178:in `block in archive_months'
     # ./app/controllers/blogs_controller.rb:177:in `select'
     # ./app/controllers/blogs_controller.rb:177:in `archive_months'

如果我在页面或 Rails 控制台中运行 @months 查询,它运行良好,但在我的测试中不起作用。

【问题讨论】:

    标签: activerecord rspec ruby-on-rails-3.2


    【解决方案1】:

    您的测试数据库中似乎有一个或多个Blog 对象没有publish_date 属性集。这就是.select{ |p| p.publish_date &lt;= Date.today } 引发错误的原因。

    【讨论】:

    • 解决此问题的方法是在每次测试后清理数据库。例如:database_cleaner
    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2012-08-31
    • 2013-04-24
    • 1970-01-01
    • 2019-12-29
    • 2013-11-14
    • 2013-01-14
    相关资源
    最近更新 更多