是否可以和/或建议在 Rails 中动态生成测试? [英] Is it possible and/or advisable to generate tests dynamically in rails?

查看:20
本文介绍了是否可以和/或建议在 Rails 中动态生成测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One trick I have found very handy in rails application programming is that class_eval can be used to create methods on the fly. I'm starting to get into testing now and I wonder if a similar idea could be used to generate tests.

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

For example, I have a before_filter to require a user to be logged in for all of the actions in a controller. I would like to write tests which ensure that the before_filter is being applied for all actions. Instead of writing out each test individually I would like to instead generate all of these test automatically.

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

Is this type of testing advisable, or should I just stick to writing the tests out individually? If it is, how would one go about doing so?

这可能看起来像:

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

既然人们已经验证了这可能有用,那么我应该将这样的代码块放在哪里,以便它只执行一次以创建这些测试?

Now that people have verified this could be useful, where would I put a block of code such as this so that it will get executed once and only once to create these tests?

推荐答案

DRY 原则适用于测试代码,就像它适用于应用程序代码一样.

The DRY principle applies to test code just as much as it applies to application code.

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

Having one method to generate all of those tests should make it easier to verify that the test is correct in the first place.

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

To answer the comment (note: I haven't written Rails test code in a while, so it probably isn't 100% correct). Everything between %| | is one big string:

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

这篇关于是否可以和/或建议在 Rails 中动态生成测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆