Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails2.3.8: Unit Testing: Rails/Ruby has setup to run before each test. What about a method that runs before all tests?

I'd like to init the data base once everytime i run tests, rather than every test. I know with Rspec there is before(:all), but I haven't been able to get that working. I was wondering if rails had something similar.

like image 688
NullVoxPopuli Avatar asked Jun 21 '11 14:06

NullVoxPopuli


2 Answers

Firstly: there used to be a before(:all) equivalent in Test::Unit but it was removed (don't know why).

Secondly: there are very good reasons not to do what you are trying to do - tests are meant to be run independently of one another, not rely on state that's in the db. This way you can guarantee that it's testing exactly what you are expecting it to test.

If you have one test that changes the state of the db, and you move it and it runs after another test which expects it to be another state - you run into problems. Thus, all test must be independent.

Thus: the db is rolled back to its pristine state and re-seeded every time.

If you really want some state that the db is always in - then set it up in the fixtures... and just realise that the db will be re-loaded for each test.

If you are having trouble with load-times... then consider figuring out some other way around the problem - eg don't use huge numbers of fixtures, instead use Factories to only create the data that you need for each individual test.

If there's some other reason... let us know - we may have a solution for it.

Edit: if you really need it, I actually wrote a monkey patch for this a long while back: "faking startup and shutdown"

like image 94
Taryn East Avatar answered Sep 18 '22 00:09

Taryn East


All things to run before everything just go in the top of the class

require 'test_helper'

class ObjectTest < ActiveSupport::TestCase
  call_rake("db:bootstrap RAILS_ENV=test")

  #set up our user for doing all our tests (this person is very busy)  
  @user = Factory(:user)
  @account = Factory(:account)    
  @user.account = @account
  @user.save

  # make sure our user and account got created 
  puts "||||||||||||||||||||||||||||||||||||||||||||||"
  puts "| propsal_test.rb"
  puts "|      #{@user.name}"
  puts "|      #{@user.account.name}"
  puts "||||||||||||||||||||||||||||||||||||||||||||||"
like image 37
NullVoxPopuli Avatar answered Sep 21 '22 00:09

NullVoxPopuli