3

I'm having some trouble stubbing current_user in a Rails functional test for a controller. I'm using Rails 4 and Minitest. Currently, in the setup block I have this line.

ApplicationController.any_instance.stubs(:current_user).returns(users(:admin))

That's kind of working; however, I'm getting the following error from my view where current_user is referenced into a routing/url helper (edit_user_path(current_user)).

ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"users", :id=>nil} missing required keys: [:id]

What is the recommended way of stubbing current_user in controller/functional test? Here's my full test.

require 'test_helper'

class Admin::SitesControllerTest < ActionController::TestCase
  setup do
    @site = sites(:test)
    @request.env['HTTP_HOST'] = "#{@site.ssl_prefix}.testing.com"
    ApplicationController.any_instance.stubs(:current_user).returns(users(:admin))
  end

  test "should show edit form" do
    get :edit, id: @site.id
    assert_response :success
    assert_template layout: "layouts/admin/layout"
  end
end
ajporterfield
  • 1,009
  • 2
  • 10
  • 23

1 Answers1

2

As always there are many ways to do this. The recommended way to stub the controller instance is to stub directly on the instance you are dealing with.

def setup
  @controller.stubs(:current_user).returns(users(:admin))
end

In controller tests you have access to the @controller instance.

Hope this helps.

pixeltom
  • 1,799
  • 1
  • 15
  • 19