代码之家  ›  专栏  ›  技术社区  ›  Bryan Ward

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

  •  3
  • Bryan Ward  · 技术社区  · 15 年前

    class_eval 可用于动态创建方法。我现在开始着手测试,我想知道是否可以使用类似的想法来生成测试。

    例如,我有一个 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
    

    2 回复  |  直到 15 年前
        1
  •  3
  •   erik    15 年前

    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
    
        2
  •  0
  •   Marnen Laibow-Koser    13 年前

    通常,单独编写测试。但是,如果您有一组相同的测试,我认为从 each 像你这样的街区。

        3
  •  0
  •   lzap    4 年前

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

    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