ruby-on-rails - 在 Rails 的 application_helper.rb 代码中测试 flash 消息方法

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

我对测试驱动开发有点陌生,我想学习如何覆盖尽可能多的代码,这样当我在 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 View 具有以下代码,使用上面的辅助方法显示 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 编写应用程序。我正在开发的应用程序的代码是 in this Github repository

最佳答案

这样的事情怎么样:

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

关于ruby-on-rails - 在 Rails 的 application_helper.rb 代码中测试 flash 消息方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16083317/

相关文章:

ruby-on-rails - Rails 管理员与事件管理员 : Rails Admin generation tools

ruby-on-rails - 使用 Rails update_all 方法用另一列中的值更新字段

java - 创建将成为另一个模拟对象的一部分的模拟对象的最佳实践

python - 在不同的 python 补丁版本上运行 tox

spring-boot - 通过在实际应用程序上运行验收测试来获取 jacoco 报告

javascript - Rails AJAX 快捷方式?

mysql - 将关联从一对多更改为多对多

javascript - 如何处理嵌套表单的条件验证?

ruby-on-rails-3 - 连接两个 mongoid 标准

ruby-on-rails-3 - 添加依赖项 :destroy in the Relationship model (Chapter 11, 练习 1 Rails 教程,第 2 版的测试)