如何在Rails插件中测试视图?
-
06-07-2019 - |
题
我正在编写一个包含一些部分内容的Rails插件。我想测试部分内容,但是我很难设置一个可以渲染它们的测试。没有相关的控制器,所以我只是假装一个:
require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'
class MyTest < Test::Unit::TestCase
def setup
@renderer = ActionController::Base.new
@renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views'))
end
def test_renders_link
result = @renderer.render(:partial => '/something')
assert ...
end
end
但:render
调用总是会爆炸。我尝试使用 ActionView :: Base
而不是 ActionController :: Base
,但这种情况甚至更少。
有没有人取得任何成功?
解决方案 2
最终答案:
require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'
require 'action_controller/test_case'
class StubController < ActionController::Base
helper MyHelper
append_view_path '...'
attr_accessor :thing
def my_partial
render :partial => '/my_partial', :locals => { :thing => thing }
end
def rescue_action(e) raise e end;
end
class MyTestCase < ActionController::TestCase
self.controller_class = StubController
def setup
@controller.thing = ...
get :my_partial
assert ...
end
end
其他提示
checkout ActionView :: TestCase - http://api.rubyonrails.org/classes /ActionView/TestCase.html
您也可以使用它们来测试助手,我发现这些助手非常有帮助。
RSpec还可以测试视图: http://rspec.info/文档/导轨/写入/ views.html
希望有所帮助!
我最接近的是
require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'
require 'action_controller/test_case'
class StubController < ActionController::Base
append_view_path '...'
def _renderizer; render params[:args]; end
def rescue_action(e) raise e end;
end
class MyTest < ActionController::TestCase
self.controller_class = StubController
def render(args); get :_renderizer, :args => args; end
def test_xxx
render :partial => ...
end
end
但是我现在收到路由错误: ActionController :: RoutingError:没有路由匹配{:action =&gt;&quot; _renderizer&quot;,:controller =&gt;&quot;&quot;,:args =&gt; {: locals =&gt; {:...} ,: partial =&gt;&quot; / my_partial&quot;}}
我建议您查看 resource_controller插件的代码。我也在其他一些插件中看到了这种方法。
答案很简单,在测试目录中,您创建了一个使用您的插件的应用。从那里,您只需使用常用工具来测试Rails视图。
如果您的插件没有很多不同的用例,测试应用程序可以非常简单。在更复杂的插件(如resource_controller)的情况下,您可能需要创建相当多的不同控制器等等。
要欺骗您的测试应用加载插件,最简单的方法是在测试应用的插件目录中创建指向r_c目录根目录的链接。这不适用于Windows,只适用于POSIX操作系统。