Hey guys! How are you?
This article is a part of a series that will teach how to create a production ready rails application. Today we're gonna talk about testing with rspec.
Table of content
What is Rspec
Rspec is a ruby gem that allow us to test our applications, it provides the best way to do TDD while developing new features.
Setting up environment
We need to follow those instructions to get rspec working:
Install the gems
group :test do
# Rspec
gem "rspec-rails", "~> 5.1.2"
# Fake data generator
gem "faker", "~> 2.23.0"
# Clean database before each test execution
gem "database_cleaner-active_record", "~> 2.0.1"
# Factories
gem "factory_bot_rails", "~> 6.2.0"
# Models specs
gem "shoulda-matchers", "~> 5.1.0"
end
Download the dependencies
bundle install
Generate Rspec configuration files
rails generate rspec:install
Require rails helper
To properly run specs we need to require rails helper on top of each spec file, to prevent this we can create a file called .rspec
in the root path of the application and put the following content there:
--require rails_helper
Configuring Rspec
Now that we have all the setup done we need to properly configure rspec, to do so we need to edit rails_helper
and spec_helper
. You'll find the full code snippet in a pull request in the end of the article, nut here's a quick explanation of some important points:
Rails Helper
This file stores all rspec general configuration and some dependencies configurations such as factory_bot and shoulda_matchers. Another important thing is that on the top of the file we have a guard clause that prevents rspec to run in a environemnt different thant test, you should never remove this safe guard
Spec Helper
This file is simpler, it contains only some inclusions and basic setup, rails_helper requires this file to improve it configuration
Test it out
Now that everything should be ok lets test it out. To do so we need to create a spec file and verify if it's passing.
Create a file under the spec
folder called test_spec.rb
and put the following content there:
RSpec.describe do
describe "rspec setup" do
it "returns true" do
expect(true).to be(true)
end
end
end
Now all you need to do is run rspec using this command:
rspec
You should look something like this if everything is ok:
You can either specify somethings to this command such as the file and line it should execute, here's an example:
rspec spec/test_spec.rb
rspec spec/test_spec.rb:3
You can see all the code changed here
Top comments (0)