ruby-on-rails - 测试 View 助手 : how do I specify a controller?

标签 ruby-on-rails testing view ruby-on-rails-3 helper

例如,考虑以下代码:

class ViewHelpersTest < ActionView::TestCase
  should 'generate tag with correct parameters' do
    assert_equal theme_stylesheet_link_tag('style', :media => 'print'),
                 '<link href="/themes/default/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />'                     
  end
end

current_theme_stylesheet_tag 是一个 View 助手,它创建一个指向位于当前主题目录内的 css 文件的样式表链接标签。可以通过调用 ApplicationController::current_theme 来检索当前主题。

因此,我需要提供一个有效的 Controller 实例,这引出了我的问题:

在 Rails 3 中测试 View 助手时,我该如何指定要使用的 Controller ?

另外,如果有更好的方式表达这个测试,请告诉我。我没有什么测试经验。

最佳答案

我不是测试助手的忠实拥护者,但如果您这样做,最好将其作为单元测试来处理,因此您希望将方法与依赖项隔离开来。在这种情况下,您无需尝试创建 Controller 对象,而只需创建模拟对象并存入必要的方法调用即可。

在 RSpec 中这可能会像这样工作,假设你的 current_theme 方法只返回一个字符串:

describe ViewHelper do
  it "should generate tag with correct parameters" do
    ApplicationController = double(:current_theme=>"A string")
    helper.my_helper_method("argument").should == "A string"
  end
end

当辅助方法执行 ApplicationController::current_theme 时,它使用 stub 而不是实际方法,因此不需要实例化 Controller ,甚至不需要 Controller 代码。

关于ruby-on-rails - 测试 View 助手 : how do I specify a controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671471/

相关文章:

javascript - Mocha 中的 "AssertionError: {} == {}"

angular - 你的一些测试做了一个完整的页面重新加载

android - 设计测试/调试的大纲 View

ruby-on-rails - ruby on rails 和 bootstrap,使 field_with_errors 水平显示

ruby-on-rails - 为 capybara 安装 webkit

ruby-on-rails - 什么 gem/library 可以处理通过 ruby​​ oauth 插件和 oauth gem 接收的 Google Calendar API 数据?

ruby-on-rails - Rails Cookie 问题

android - 如何使用 mockk 模拟 Build.VERSION.SDK_INT

swift - 如何将一个 SwiftUI View 作为变量传递给另一个 View 结构

mysql - 将附加列和子查询添加到 MySQL VIEW 以创建现有表的更具可读性的版本