gpt4 book ai didi

ruby-on-rails - Rails 插件的功能测试,assert_template 损坏了吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:09 25 4
gpt4 key购买 nike

我正在编写一个向 ActionController::Base 添加类方法的插件,因此在我的功能测试中,我创建了一个简单的 Controller 来进行测试。下面的示例被完全精简为基本上什么都不做。测试一直成功到 assert_template,但失败了。

require 'rubygems'
require 'test/unit'
require 'active_support'
require 'active_support/test_case'
require 'action_controller'
require 'action_controller/test_process'

class UnderTestController < ActionController::Base
def index; end
end
ActionController::Routing::Routes.draw {|map| map.resources :under_test }

class MyPluginTest < ActionController::TestCase
def setup
@controller = UnderTestController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end

test "should render the correct template" do
get :index
assert_template :index # everything works except this assert
end
end

下面是运行上述文件的结果:

Loaded suite /Users/jjulian/sandbox/vendor/plugins/my_plugin/test/my_plugin_test
Started
E
Finished in 0.014567 seconds.

1) Error:
test_should_render_the_correct_template(MyPluginTest):
NoMethodError: undefined method `[]' for nil:NilClass
method assert_template in response_assertions.rb at line 103
method clean_backtrace in test_case.rb at line 114
method assert_template in response_assertions.rb at line 100
method test_should_render_the_correct_template in so_test.rb at line 22
method __send__ in setup_and_teardown.rb at line 62
method run in setup_and_teardown.rb at line 62

1 tests, 0 assertions, 0 failures, 1 errors

我的问题:为了让 assert_template 起作用,我错过了什么?我需要正确的库吗?扩展正确的 TestCase 类?

最佳答案

我想通了。首先,缺少模板是因为 view_path 需要在被测 Controller 中显式设置:

before_filter {|c| c.prepend_view_path(File.join(File.dirname(__FILE__), 'fixtures')) }

我在 test/fixtures/under_test/index.erb 中创建了一个虚拟 erb 文件。这让我回到了 response_assertions.rb 中的 nil 错误。好吧,看来我需要包含另一个测试类:

require 'action_view/test_case'

现在可以了。

一个补充说明:assert_template 使用 match 来确定成功,所以在这种情况下,assert_template 'ind' 会成功,assert_template 'x'

关于ruby-on-rails - Rails 插件的功能测试,assert_template 损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1776671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com