Reputation: 353
Rails 5.1.6 Ruby 2.5.0
I am trying to run a simple test for a redirect in one of my controllers using Shoulda Matcher gem (following the documentation) and minitest:
home_controller.rb:
class HomeController < ApplicationController
def index
#redirect on login
if user_signed_in?
redirect_to controller: 'home', action: "dashboard_#{current_user.user_role}"
end
end
test/controllers/home_controller_test.rb:
class HomeControllerTest < ActionController::TestCase
context 'GET #index' do
setup { get :index }
should redirect_to(action: "dashboard_#{current_user.user_role}")
end
end
Error:
Undefined method current_user for homecontrollertest
I'm using Devise and was wondering if anyone could assist to get my test to work? I can provide more info if required.
EDIT:
Tried this:
home_controller_test.rb
require 'test_helper'
class HomeControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
context 'GET #index' do
user = users(:one)
sign_in user
get :index
should redirect_to(action: "dashboard_#{user.user_role}")
end
end
users.yml
one:
name: 'John'
email: '[email protected]'
encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
user_role: 1
Gemfile
gem 'shoulda', '~> 3.5'
gem 'shoulda-matchers', '~> 2.0'
Test_helper.rb
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
Get undefined method users error.
NoMethodError: undefined method `users' for HomeControllerTest:Class
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:9:in `block in <class:HomeControllerTest>'
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:8:in `<class:HomeControllerTest>'
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:4:in `<top (required)>'
Tasks: TOP => test
(See full trace by running task with --trace)
Upvotes: 0
Views: 442
Reputation: 4640
You need to include devise test helper to your test
class HomeControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
context 'GET #index' do
user = users(:one) # if you use fixtures
user = create :user # if you use FactoryBot
sign_in user
get :index
should redirect_to(action: "dashboard_#{user.user_role}")
end
end
Upvotes: 1