Theo Chirica
Theo Chirica

Reputation: 4516

Failure/Error: get :index NoMethodError: undefined method `<=' for nil:NilClass

I hope this is not a specific error and it may be a logic error that can help others as well.

I want to test my controller index method, and i have a before method with an active record query. The problem is that i can't figure what is wrong with my test because i get this error only when using rspec and not when i test it manually.

Controller

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

Test

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

Test output

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'

If i run the @months query on the page or in rails console it works well, but on my test in does not work.

Upvotes: 1

Views: 270

Answers (1)

tbuehlmann
tbuehlmann

Reputation: 9110

It seems you have one or more Blog objects in your test database that don't have a publish_date attribute set. That's why .select{ |p| p.publish_date <= Date.today } raises the error.

Upvotes: 1

Related Questions