Tef*_*Ted 19 testing methods ruby-on-rails helper
它们似乎无法从ActionView :: TestCase访问
Jon*_*ian 34
没错,辅助方法不会在视图测试中公开 - 但可以在功能测试中测试它们.由于它们是在控制器中定义的,因此这是测试它们的正确位置.您的辅助方法可能被定义为private,因此您必须使用Ruby元编程来调用该方法.
应用程序/控制器/ posts_controller.rb:
class PostsController < ApplicationController
private
def format_something
"abc"
end
helper_method :format_something
end
Run Code Online (Sandbox Code Playgroud)
测试/功能/ 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
Run Code Online (Sandbox Code Playgroud)
这感觉很尴尬,因为您通过在私有方法上使用 send 来绕过封装。
更好的方法是将辅助方法放在 /controller/concerns 目录中的模块中,并专门为此模块创建测试。
例如在应用程序控制器/posts_controller.rb中
class PostsController < ApplicationController
include Formattable
end
Run Code Online (Sandbox Code Playgroud)
在应用程序/控制器/关注/formattable.rb
module Concerns
module Formattable
extend ActiveSupport::Concern # adds the new hot concerns stuff, optional
def format_something
"abc"
end
end
end
Run Code Online (Sandbox Code Playgroud)
并在测试/功能/关注/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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10677 次 |
| 最近记录: |