How do you setup a Rails project for testing? In this article we will explore what a testing suite, using RSpec and other tools, for a robust developers experience. This article touches on my approaches to testing tools as I have been focused on learning RSpec.
Basic project setup.
First we need to start a rails project. We will use the -T switch to exclude testing since we will opt for RSpec over the Rails default of minitest. We will also default to Postgres for our database. This is not required, just my preference:
rails new rails_testing_setup -T --database=postgresql
Create and migrate the databases.
rails db:prepare && rails db:migrate
You can start the rails server and see the familiar Rails splash screen.
Basic Testing
To set up testing we are going to use RSpec, which according to the RSpec web site: "Behaviour Driven Development for Ruby. Making TDD Productive and Fun." I am not sure about all of that, but it is what we are setting up.
Basic RSpec setup
We will add two gems to your Gemfile in the development and test group, RSpec and Capybara, which helps you test web applications by simulating how a real user would interact with your app.:
group :development, :test do
...
gem "capybara", ">= 2.15"
gem "rspec-rails"
...
end
If by chance, you forgot to exclude the testing framework on the rails setup, make sure you delete the test directory. It doesn't hurt anything, but it is a best practice not to include two testing directories. Then setup RSpec: rails g rspec:install. This will install a spec directory with a couple of helper files.
Now, we need to clean up and add some configuration to the rails_helper.rb file. I start by cleaning out all the comments, but that is just me. Then update the RSpec.configuration block:
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
also add a require at the top of the file below rails for capybara:
require "rspec/rails"
require "capybara/rails"
If you run rspec everything should be green and ok, since we have no test.
Database Cleaner I also want to make sure the test database is a clean slate, so we need to add the gem database_cleaner to the development and test group, which should now look so:
group :development, :test do
gem 'byebug', platforms: %i[mri mingw x64_mingw]
gem "capybara", ">= 2.15"
gem 'database_cleaner'
gem 'rspec-rails'
end
Sharing Is Caring If you knew Better Article Related to this topic, please share it in the comments
This Site is all about collection of best resources
Users able to write own articles or share the resources they know
If you found any copy right issues, kindly CONTACT US. will take Immediate Action.