Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Flush table / destroy objects after each context

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 ==)
like image 360
migu Avatar asked Jan 16 '13 19:01

migu


1 Answers

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

like image 189
Leo Correa Avatar answered Sep 29 '22 05:09

Leo Correa