Cleaning the Database with Truncation

Truncating the database before each scenario is a brute-force technique, and the main drawback is that it’s generally slower than rolling back a transaction. This is why the transactional approach is generally preferable if you can get away with it. The advantage of truncation is that it’s a cleaning strategy that works reliably when we have more than one database connection, since no transactions are used. Let’s modify our cleaning strategy and see how it compares. This is a simple change in our database.rb file, shown below.

Joe asks:
Joe asks:
Why Not Truncate the Database in an After Hook?

Truncating the database in an After hook usually works just as well as doing it in a Before hook, but there is a subtle difference.

First, if the process gets killed before it has time to clean up in the After hook, it might cause the next test run to fail.

Second, when a scenario fails it might not be evident why it failed, and having the ability to peek inside the database as a post-mortem often helps us understand why a scenario is failing.

As you will also see in Isolating Scenarios, this post-mortem technique can be used in other situations as well.

 require ​'database_cleaner'
 
 DatabaseCleaner.strategy = ​:truncation
 
 Before ​do
  DatabaseCleaner.clean
 end

Notice how we removed the After hook and made the Before hook call DatabaseCleaner.clean instead. In truncation mode, DatabaseCleaner.start does nothing, and DatabaseCleaner.clean truncates all tables. In other words, it deletes all rows.

Running Cucumber again makes the scenario pass again:

 == 1 CreateAccounts: migrating ================================================
 -- create_table(:accounts)
  -> 0.0010s
 == 1 CreateAccounts: migrated (0.0010s) =======================================
 
 Starting transaction_processor in ~/message_queues/01 with
  'ruby lib/transaction_processor.rb'
 transaction processor ready
 Server transaction_processor (94557) is up.
 Feature: Cash Withdrawal
 
  Scenario: Successful withdrawal from an account in credit
  Given my account has been credited with $100
  When I withdraw $20
  Then $20 should be dispensed
  And the balance of my account should be $80
 
 1 scenario (1 passed)
 4 steps (4 passed)
 0m2.076s
 Shutting down transaction_processor (94557)
 Server transaction_processor (94557) is shut down

That brings us to the end of the worked example. In the next part are a series of recipes for using Cucumber in the wild. Good luck out there!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.26.138