什么是单元/助手 - 从ActionView :: TestCase继承的类?

时间:2012-09-30 05:19:46

标签: ruby-on-rails testing helpers

我无法在Rails指南或使用Rails的敏捷Web开发中找到这些通常称为HelperTest的类。 搜索网似乎显示大多数人使用它们来测试帮助者。 但是为什么脚手架会为每个模型类创建其中一个呢? 为什么它被置于测试\单位? 我将感谢一个很好的例子,说明应该在何处以及如何使用它们。 如果不使用脚手架生成的帮助文件,那么它是否错误? 提前致谢

1 个答案:

答案 0 :(得分:1)

正如您所指出的,脚手架生成器(此处为'posts')在test/unit/helpers下创建帮助器测试:

test
├── fixtures
│   └── posts.yml
├── functional
│   └── posts_controller_test.rb
├── integration
├── performance
│   └── browsing_test.rb
├── test_helper.rb
└── unit
    ├── helpers
    │   └── posts_helper_test.rb
    └── post_test.rb

它们是单元测试,因为助手只是应该单独测试的方法;另外,如果您认为视图应该保持轻量级,这可能意味着帮助程序最终会有很多逻辑,并且应该像模型一样进行测试。

所以,给这个助手(在app / helpers / posts_helper.rb中)

module PostsHelper

  def hello
    content_tag :div, :class => "detail" do
      "hi"
    end
  end
end

你可以这样写一个测试:

require 'test_helper'

class PostsHelperTest < ActionView::TestCase

  test "hello" do
    assert_equal(hello, "<div class=\"detail\">hi</div>")
  end

end

它们只是方法,因此请使用与任何单元测试相同的匹配器(assert_equalassert_match); assert_dom_equal在这里也派上用场了。 (见http://cheat.errtheblog.com/s/assert_dom_equal/

我希望这会有所帮助:)

凯尔

相关问题