RSpec: Flush table / destroy objects after each context

migu picture migu · Jan 16, 2013 · Viewed 7.4k times · Source

How do you delete the objects (in the database and in the memory) you created

  • after each test
  • AND after each context? (in a context it could make sense to build tests on each other)

Is there a method to do this automatically?

I have the following problem:

Each test saves entries to the database. The next test then depends on these entries. Even if I wanted to build tests that are dependent on other tests, I couldn't, because the order in which the tests get executed is not controllable.

factories.rb:

sequence(:name) { |n| "purchaser #{n}" }      

organization_spec.rb:

context "when no supplier exists" do
  it "finds no associated suppliers" do
    purchaser = create(:organization_purchaser)                
    purchaser.partners.empty?.should == true
  end
end

context "when one supplier exists" do
  it "finds one associated suppliers" do
    purchaser = create(:organization_purchaser)      
    supplier = create(:organization_supplier)
    partnership = create(:partnership, organization: purchaser, partner: supplier)         
    purchaser.partners.last.name.should == "purchaser 1"
  end
end

context "when two suppliers exist" do        
  it "finds two associated suppliers" do
    purchaser = create(:organization_purchaser)      
    2.times do |i|
      supplier = create(:organization_supplier)
      partnership = create(:partnership, organization: purchaser, partner: supplier) 
    end    
    purchaser.partners.last.name.should == "purchaser 2"
  end
end

RSpec output:

Organization
  #suppliers_for_purchaser
    responds
    when no supplier exists
      finds no associated suppliers
    when two suppliers exist
      finds two associated suppliers
    when one supplier exists
      finds one associated suppliers (FAILED - 1)

Failures:

1) Organization#suppliers_for_purchaser when one supplier exists finds one associated suppliers
 Failure/Error: purchaser.partners.last.name.should == "purchaser 1"
   expected: "purchaser 1"
        got: "purchaser 3" (using ==)

Answer

Leo Correa picture Leo Correa · Jan 16, 2013

You should use Database Cleaner

All you have to do is add the following code to your Rspec configuration file spec_helper.rb

config.before(:suite) do
  DatabaseCleaner.strategy = :transaction
  DatabaseCleaner.clean_with(:truncation)
end

config.before(:each) do
  DatabaseCleaner.start
end

config.after(:each) do
  DatabaseCleaner.clean
end

UPDATE

As of Rails 5.1 this is not needed if you use config.use_transactional_tests

https://github.com/rails/rails/pull/19282