【问题标题】:Testing flash message method in application_helper.rb code in Rails在 Rails 的 application_helper.rb 代码中测试 flash 消息方法
【发布时间】:2013-04-11 14:08:45
【问题描述】:

我对测试驱动开发有点陌生,我想学习如何覆盖尽可能多的代码,这样当我在 Rails 中制作更复杂的应用程序时,我将能够防止引入错误。

我在application_helper.rb 中有一些代码,用于将 Flash 消息样式化到 Twitter Bootstrap 类,我想为我编写的代码编写一个测试,所以如果有任何变化,我会在它成为一点问题之前知道它。

#application_helper.rb
module ApplicationHelper
  def flash_class(type)
    case type
    when :alert
      "alert-error"
    when :notice
      "alert-info"
    else
      ""
    end
  end
end

我的application.html.erb 视图具有以下代码,用于使用上面的帮助方法显示 Flash 消息。

#application.html.erb
<% flash.each do |type, message| %>
  <div class="alert <%= flash_class type %>">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <%= message %>
  </div>
<% end %>

我将编写什么类型的测试来测试application_helper.rb 中的代码是否有效,我将如何编写该测试?我也在使用 shoulda-context gem 进行测试编写,但我不在乎测试是否使用标准 Rails test_with_lots_of_underscores 样式编写。

我正在使用Cloud9 使用 Ruby 1.9.3(补丁级别 327)和 Rails 3.2.13 编写应用程序。我正在开发的应用程序的 repoosiroty 是 in this Github repository

【问题讨论】:

  • 单独测试辅助方法
  • 我该怎么写呢?我写过的唯一测试是表单验证的单元测试:(
  • @apneadiving 虽然这个答案在更广泛的范围内很好,但我真的只想有一个可以在现有代码中实现的示例,以便更好地理解它的机制。

标签: ruby-on-rails ruby-on-rails-3 testing


【解决方案1】:

这样的事情怎么样:

class ApplicationHelperTest < Test::Unit::TestCase
  context "flash_class" do

    should "map :alert symbol to 'alert-error' string" do
      assert_equal 'alert-error', flash_class(:alert)
    end

    should "map :notice symbol to 'alert-info' string" do
      assert_equal 'alert-info', flash_class(:notice)
    end

    should "map anything else to empty string" do
      assert_equal '', flash_class(:blah)
    end

  end
end

【讨论】:

  • 我运行了那个测试,它返回了test/application_helper_test.rb:1:in '&lt;main&gt;': uninitialized constant Test (NameError)
  • 我给出了大致的想法。我以前从未使用过 shoulda-context,所以我不熟悉如何将它与 Rails 应用程序集成。您还有其他有效的测试吗?
  • Should-context 可以与正常的 Rails 测试结合使用。 This file on Github 包含我为表单验证编写的一些测试。
  • 好吧,看起来你的测试是从 ActiveSupport::TestCase 继承的。你在这里也试过吗?
  • 我已经尝试使用 class ApplicationHelperTest &lt; ActiveSupport::TestCase 打开测试,这就是您所得到的,并且返回与以前相同的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 2019-09-23
相关资源
最近更新 更多