Rails: запрос соответствия, Minitest и Devise - PullRequest
0 голосов
/ 13 мая 2018

Рельсы 5.1.6 Ruby 2.5.0

Я пытаюсь запустить простой тест для перенаправления в одном из моих контроллеров, используя gem-файл Shoulda Matcher (следуя документации) и 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

тест / контроллеры / 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

Ошибка:

Undefined method current_user for homecontrollertest

Я пользуюсь Devise, и мне было интересно, кто-нибудь может помочь заставить мой тест работать? Я могу предоставить больше информации, если требуется.

EDIT:

Попробовал это:

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: 'some@user.com'
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

Ошибка неопределенного пользователя метода.

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)

1 Ответ

0 голосов
/ 13 мая 2018

Вы должны включить в свой тест devise test helper

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
...