Подтвердить что ты не робот

Как вы тестируете метод контроллера Rails, открытый как helper_method?

Они, кажется, не доступны из ActionView:: TestCase

4b9b3361

Ответ 1

Это правильно, вспомогательные методы не отображаются в тестах просмотра, но они могут быть протестированы в ваших функциональных тестах. И поскольку они определены в контроллере, это подходящее место для их проверки. Ваш вспомогательный метод, вероятно, определяется как private, поэтому вам нужно будет использовать метапрограммирование Ruby для вызова метода.

приложение/контроллеры/posts_controller.rb:

class PostsController < ApplicationController

  private

  def format_something
    "abc"
  end
  helper_method :format_something
end

Тест/функционал/posts_controller_test.rb:

require 'test_helper'

class PostsControllerTest < ActionController::TestCase
  test "the format_something helper returns 'abc'" do
    assert_equal 'abc', @controller.send(:format_something)
  end
end

Ответ 2

Это неудобно, потому что вы обходите инкапсуляцию с помощью отправки по частному методу.

Лучший подход заключается в том, чтобы помещать вспомогательный метод в модуль в каталог/controller/озабоченности и создавать тесты специально для этого модуля.

например. в контроллере приложений /posts _controller.rb

class PostsController < ApplicationController
  include Formattable
end

в приложении/контроллере/проблемы/formattable.rb

  module Concerns
    module Formattable
      extend ActiveSupport::Concern # adds the new hot concerns stuff, optional

      def format_something
        "abc"
      end
    end
  end

И в test/functional/issues/formattable_test.rb

require 'test_helper'

# setup a fake controller to test against
class FormattableTestController
  include Concerns::Formattable
end

class FormattableTest < ActiveSupport::TestCase

 test "the format_something helper returns 'abc'" do
    controller = FormattableTestController.new
    assert_equal 'abc', controller.format_something
  end

end

Ответ 3

Вы можете проверить @controller.view_context на своих тестах на функциональность/контроллер. Насколько мне известно, этот метод доступен в Rails 3, 4 и 5.

приложение/контроллеры/application_controller.rb

class ApplicationController < ActionController::Base
  helper_method :current_user
  # ...
end

тест/контроллеры/application_controller_test.rb

require 'test_helper'

class ApplicationControllerTest < ActionController::TestCase
  test 'current_user helper exists in view context' do
    assert_respond_to @controller.view_context, :current_user
  end
end

Если вы не хотите тестировать один из подклассов вашего контроллера, вы также можете создать контрольный контроллер, чтобы убедиться, что метод в view_context является тем же самым из контроллера, а не из одного из ваших помощников вида.

class ApplicationControllerHelperTest < ActionController::TestCase
  class TestController < ApplicationController
    private
    def current_user
      User.new
    end
  end

  tests TestController

  test 'current_user helper exists in view context' do
    assert_respond_to @controller.view_context, :current_user
  end

  test 'current_user returns value from controller' do
    assert_instance_of User, @controller.view_context.current_user
  end
end

Или, скорее всего, вы захотите проверить помощника при наличии запроса.

class ApplicationControllerHelperTest < ActionController::TestCase
  class TestController < ApplicationController
    def index
      render plain: 'Hello, World!'
    end
  end

  tests TestController

  def with_routing
    # http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-with_routing
    # http://guides.rubyonrails.org/routing.html#connecting-urls-to-code
    super do |set|
      set.draw do
        get 'application_controller_test/test', to: 'application_controller_test/test#index'
      end

      yield
    end
  end

  test 'current_user helper exists in view context' do
    assert_respond_to @controller.view_context, :current_user
  end

  test 'current_user returns value from controller' do
    with_routing do
      # set up your session, perhaps
      user = User.create! username: 'testuser'
      session[:user_id] = user.id

      get :index
      assert_equal user.id, @controller.view_context.current_user.id
    end
  end
end

Ответ 4

Действительно, это не так. Тестирование просмотра предназначено специально для представлений. Они не загружают контроллеры.
Вы должны издеваться над этим методом и вернуть его в зависимости от вашего контекста.

Ответ 5

Я немного боролся с этим, потому что принятый ответ фактически не проверял, был ли метод выставлен как вспомогательный метод.

Тем не менее, мы можем использовать метод #helpers, чтобы получить прокси для тестирования.

Например:

class FooController < ApplicationController
  private

  def bar
    'bar'
  end

  helper_method :bar
end

Можно протестировать с помощью:

require 'test_helper'

class FooControllerTest < ActionController::TestCase
  test 'bar is a helper method' do
    assert_equal 'bar', @controller.helpers.bar
  end
end