Home > Net >  Ruby on Rails how to fix NoMethodError: undefined method `id' for nil:NilClass
Ruby on Rails how to fix NoMethodError: undefined method `id' for nil:NilClass

Time:01-12

I'm trying to run a test on my Response controller, where nobody is logged in and the app should redirect to the login url if someone tries to post a valid response to a prayer Request without being logged in first. I have some test requests in the requests.yml file, and when I try to use one of them in the test code, trying to pull it's id, I get an error saying I have a NilClass error and cannot get the id.

This is my test code:

require "test_helper"

class ResponsesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @request = requests(:askingfororange)
    @response = responses(:responsetoorange)
    @user = users(:michael)
  end

  test "should redirect create when not logged in" do
    assert_no_difference 'Response.count' do
      post responses_path, params: { response: { content: "Lorem ipsum",
                                                user_id: @user.id,
                                                request_id: @request.id } }
    end
    assert_redirected_to login_url
  end

end

this is my requests.yml file:


askingfororange:
  content: "I need more oranges in my life. Please pray."
  created_at: <%= 10.minutes.ago %>
  user: michael

askingaboutpi:
  content: "Does pi matter in spirituality? Please pray for me to know!"
  created_at: <%= 3.years.ago %>
  user: michael

askingforcat:
  content: "Do cats help with spiritual health? Pray for me to find out!"
  created_at: <%= 2.hours.ago %>
  user: michael

askingforlime:
  content: "I need more limes in my life, please pray."
  created_at: <%= 3.days.ago %>
  user: archer

most_recent:
  content: "My most recent prayer request is... tada!"
  created_at: <%= Time.zone.now %>
  user: michael

<% 30.times do |n| %>
request_<%= n %>:
  content: <%= Faker::Lorem.sentence(word_count: 15) %>
  created_at: <%= 42.days.ago %>
  user: michael
<% end %>

When I run my test suite, I get the following:

ERROR ResponsesControllerTest#test_should_redirect_create_when_not_logged_in (0.36s)
Minitest::UnexpectedError:         NoMethodError: undefined method `id' for nil:NilClass

                                                        request_id: @request.id } }
                                                                            ^^^

CodePudding user response:

@request is already in use by ActionDispatch::IntegrationTest, and it is reset to nil at the top of every test. Pick a different variable name.

See https://github.com/rails/rails/blob/8015c2c2cf5c8718449677570f372ceb01318a32/actionpack/lib/action_dispatch/testing/integration.rb#L152

  • Related