TradeRaider
TradeRaider

Reputation: 754

What happens to model objects created in tests?

My curiosity won't let me keep my mouth shut. Here is a bit of code from Rails Tutorial.

 describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit user_path(user) }

    it { should have_selector('h1',    text: user.name) }
    it { should have_selector('title', text: user.name) }
  end

What happens to the Factory object created here after the test returns true or false. The above code would save an object to the database, but does it automagically get rolled back after running the tests or does Rails do something else with it :P I was just wondering because

 $ rails console test
 > User.all

would return nothing, but an empty array.

Upvotes: 1

Views: 94

Answers (1)

Michael Papile
Michael Papile

Reputation: 6856

Usually when you do rails generate for rspec, it will place this in your spec_helper.rb

  RSpec.configure do |config|
     config.use_transactional_fixtures = true
  end

This means Rspec will use a transaction with every test, and roll it back after so you have a clean database between each test. If you set this to false it will not do this.

Factory.create does indeed persist the record to the database, but it will roll back after the test is run. So if you look for the record after the test, it is no longer there.

In general this is the best practice as there should not be dependencies across tests, and each test should test one thing.

Upvotes: 3

Related Questions