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

时间:2013-04-18 12:44:21

标签: 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视图包含以下代码,可以使用上面的帮助方法显示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

1 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

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