Durham Smith
Durham Smith

Reputation: 157

Devise and testing NoMethodError: undefined method `env' for nil:NilClas

I am using devise for my user authentication. When I try to write tests for following a project (the functionality works) I get the following error

    ERROR["test_should_be_valid", FollowRelationshipTest, 0.245433]
 test_should_be_valid#FollowRelationshipTest (0.25s)
NoMethodError:         NoMethodError: undefined method `env' for nil:NilClass

However if I remove include Devise::TestHelpers from test/test_helper.rb I get no such errors.

However this introduces new errors such as

 ERROR["test_should_create_project", ProjectsControllerTest, 0.331449]
 test_should_create_project#ProjectsControllerTest (0.33s)
NoMethodError:         NoMethodError: undefined method `authenticate' for nil:NilClass
            app/controllers/projects_controller.rb:28:in `create'
            test/controllers/projects_controller_test.rb:21:in `block (2 levels) in <class:ProjectsControllerTest>'
            test/controllers/projects_controller_test.rb:20:in `block in <class:ProjectsControllerTest>'


        app/controllers/projects_controller.rb:28:in `create'
        test/controllers/projects_controller_test.rb:21:in `block (2 levels) in <class:ProjectsControllerTest>'
        test/controllers/projects_controller_test.rb:20:in `block in <class:ProjectsControllerTest>

These new errors seem to stem from calling methods such as current_user in the views (e.g <%= current_user.email if current_user %> produces the error)

What I would like to know is how to be able to get rid of the errors NoMethodError: undefined method `env' for nil:NilClas while still being able to access methods introduced by Devise::TestHelpers

FollowRelationshipTest is as follows

require 'test_helper'
class FollowRelationshipTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
  def setup
    @follow_relationship = FollowRelationship.new(follower_id: 1, project_id: 1)
  end

  test "should be valid" do
    assert @follow_relationship.valid?
  end
end

and ProjectsControllerTest is the same as what is generated with the scaffolding command

Upvotes: 0

Views: 663

Answers (1)

harald
harald

Reputation: 6126

Sorry for the late reply, but in case anybody else stumbles across the same:

The Devise::TestHelpers should only be included for controller tests, so you need to move it to the ActionController::TestCase by adding this to your test helpers:

class ActionController::TestCase
  include Devise::TestHelpers
end

Upvotes: 1

Related Questions