Search code examples
ruby-on-railsrubyunit-testingfunctional-testing

Is it okay to run for loops in functional test methods?


Is it okay (conceptually) to run for loops in test methods?

I'd like to test a range of parameter values into a controller, to determine if the different inputs return the correct values.

  test "logged in user - add something - 0 qty" do
    @app = Factory.create(:app)

    (0..5).each do |t|
      @qty = t
      login(:user)
      get :add. :id => @app.id, :qty => @qty
      assert_nil(flash[:error])
      assert_response :redirect
      assert_redirect_to :controller => :apps, :action => :show, :id => @app.id
      if @qty = 0 
        assert_equal(Invite.all.count, @qty + 1)
      else 
        assert_something .........
    end
  end

Something like that.


Solution

  • I usually try to avoid any kind of conditional statements or loops in test code. You want your tests to be as simple as possible, and if you start including logic in your tests you have to test them to make sure they work as designed. I would break the loop up into separate test cases, that way if any one of them fails it's easier to pinpoint exactly what inputs caused the failure. When a test fails it should be immediately obvious what caused it. You shouldn't have to analyze the test code to figure it out.

    Update:

    I do want to add that there are some extremely rare cases where you would want to have a loop in your test cases. One specific example is when you're testing for concurrency issues. This is an exception to the general rule, and you should have a very good and well-understood reason for having any kind of logic in your tests.