Is it possible and / or expedient to dynamically generate tests in rails?

One trick that I found very convenient in rails programming is that class_evalyou can use it to create methods on the fly. I'm starting to test now, and I'm wondering if you can use a similar idea to create tests.

For example, I have before_filterto require that a user be registered for all actions in the controller. I would like to write tests that guarantee that it before_filterapplies to all actions. Instead of recording each test separately, I would like to automatically generate all these tests.

Is this type of testing appropriate, or should I just stick to writing tests individually? If so, how to do it?

EDIT: It might look something like this:

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 confirmed that this can be useful, where would I put a block of code, for example, so that it runs once and only once to create these tests?

+3
source share
2 answers

The DRY principle applies to test code in the same way as to application code.

Having one method to create all of these tests should make it easier to verify the test.

(: 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
+3

, . , , each, , .

: RSpec, Test:: Unit. , , , .

0

Source: https://habr.com/ru/post/1712771/


All Articles