Reydan
Reydan

Reputation: 33

Is there a way to force the order of tests in Rails?

I have an ideas_test.rb file with 2 tests

test "create new idea" do
end
test "that Ideas are loaded in the index" do
end

When I run rails test test/system/ideas_test.rb, the 2nd test is executed first. Why is that? Is there a way to force the order of tests? Is the DB cleared between each Test?

Thanks in advance.

Upvotes: 3

Views: 1211

Answers (2)

Paulo Abreu
Paulo Abreu

Reputation: 1786

Test theory says that tests shouldn't have dependencies, meaning that when you run a test it shouldn't depend on another test to pass.

The best way to make sure that we catch dependencies is to run tests in random order.

As others said, you can force tests to run in the provided order, but that is considered a bad practice and I highly recommend you to stay away from it.

Update:

All fixtures, objects persisted in setup (def setup) and in the test (test "..." do) will be discarded at the end of the test. You can inspect the log/test.log ($ tail -f log/test.log) to see that in action. That ensures that tests won't affect each other. Each test starts with the assumption of a clean database.

Read https://api.rubyonrails.org/v6.1/classes/ActiveRecord/FixtureSet.html for more details

Upvotes: 3

edurante
edurante

Reputation: 71

As of Rails 5.0, ActiveSupport is configured to run tests in random order by default. You can change that default with a configuration setting, config.active_support.test_order = :sorted in your test environment: https://guides.rubyonrails.org/v5.0/configuring.html#configuring-active-support.

Your test database will not be automatically cleared between tests. Most folks use a gem like Database Cleaner for this purpose.

Upvotes: 4

Related Questions