是否可以和/或建议在rails中动态生成测试?

时间:2009-07-16 13:28:14

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

我发现在rails应用程序编程中非常方便的一个技巧是class_eval可用于动态创建方法。我现在开始进行测试,我想知道是否可以使用类似的想法来生成测试。

例如,我有before_filter要求用户登录控制器中的所有操作。我想编写测试,以确保before_filter适用于所有操作。我不想单独写出每个测试,而是自动生成所有这些测试。

这种类型的测试是否可取,或者我应该坚持单独编写测试?如果是的话,怎么会这样做呢?

编辑:这可能类似于:

actions = {:index => :get,:show => :get,:edit => :get,:update => :put}
actions.each_pair do |action,type|
  class_eval(%Q{def test_user_required_for_#{action}
      set_active_user users(:one)
      #{type} :#{action}
      assert flash[:error]
      assert_redirected_to :action => :index
    end
  })
end

既然人们已经证实这可能有用,我会在哪里放一个代码块,这样它会被执行一次而且只执行一次来创建这些测试?

3 个答案:

答案 0 :(得分:3)

DRY原则适用于测试代码,与应用程序代码一样多。

使用一种方法生成所有这些测试应该可以更容易地验证测试是否正确。

回答评论(注意:我有一段时间没有写过Rails测试代码,所以它可能不是100%正确)。 %| |之间的所有内容都是一个大字符串:

MyControllerTest

  [:index, :show, :new, :create, :edit, :update, :destroy].each do |action|
      class_eval do %|
        test "#{action} requires before filter" do
          #test #{action} code here
        end
      |
  end

end

答案 1 :(得分:0)

通常,单独编写测试。但是,如果你有一堆相同的测试,我认为从each块生成每个测试都没有错。

奖金提示:使用RSpec,而不是Test :: Unit。除了通常更好,它使你正在做的事情变得更容易。

答案 2 :(得分:0)

在使用 class_eval DSL 时没有理由使用 test

class MyControllerTest
  [:index, :show, :new, :create, :edit, :update, :destroy].each do |action|
    test "#{action} requires before filter" do
      #test #{action} code here
    end
  end
end