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



我对测试驱动开发有点陌生,我想学习如何覆盖尽可能多的代码,这样当我在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视图有以下代码来使用上面的helper方法显示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中的代码是否工作,我该如何编写该测试?我还使用应该上下文gem进行测试编写,但我不关心测试是否以标准Rails test_with_lots_of_underscores风格编写。

我使用Cloud9用Ruby 1.9.3(补丁级别327)和Rails 3.2.13编写应用程序。我正在开发的应用程序的reoosiroty在这个Github存储库

这样如何:

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

最新更新