Transactions and Database Setup

Understanding Transactions and Database Setup

Transactions and Database Setup

Let’s understand Transactions and Database Setup.  Some Capybara drivers need to run against an actual HTTP server. Capybara takes care of this and starts one for you in the same process as your test, but on another thread. Selenium is one of those drivers, whereas RackTest is not.

If you are using a SQL database, it is common to run every test in a transaction, which is rolled back at the end of the test, rspec-rails does this by default out of the box for example. Since transactions are usually not shared across threads, this will cause data you have put into the database in your test code to be invisible to Capybara.

Cucumber handles this by using truncation instead of transactions, i.e. they empty out the entire database after each test. You can get the same behaviour by using a gem such as database_cleaner.

It is also possible to force your ORM to use the same transaction for all threads. This may have thread safety implications and could cause strange failures, so use caution with this approach. It can easily implement in ActiveRecord through the following monkey patch:

class ActiveRecord::Base

mattr_accessor :shared_connection

@@shared_connection = nil

 

def self.connection

@@shared_connection || retrieve_connection

end

end

ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection

Make your resume stand out and become a Certified Capybara Testing Professional. Try free practice tests here!

A great career is just a certification away. So, practice and validate your skills to become Certified Capybara Testing Professional

Matching
XPath CSS and selectors

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?