Now that I've managed to complete the Rails tutorial, I'd like to introduce RSpec. First, I will introduce RSpec itself and the frameworks that accompany it.
RSpec is a testing framework for behavior-driven development in Ruby (wikipedia excerpt)
Behavior-driven development seems to be a development method in which the behavior is created first and the code is written later. In other words, you create something like a specification that describes the operation in advance, and implement the function according to it. It may be more like "writing a specification" than "writing a test".
Capybara
capybara is a testing framework that has been included since Rails 5.1. By combining with RSpec, it will automatically perform the browser operation that people actually check manually.
FactoryBot
FactoryBot is a gem that supports the creation of test data. There is a similar thing called Fixture that is included in the Rails standard for creating test data. Fixture can be described in YAML format with a structure similar to a database, but it is not good at complicated data control. On the other hand, Factory Bot makes it easier to control the state and relationships of data by using ActiveRecord callbacks. I interpreted Fixture as cutting out a scene from the database and FactoryBot as describing the movement of the data. If you make a mistake, please point it out.
First, add a gem called rspec-rails to the test of the Gemfile.
Gemfile.
gem 'rspec-rails'
$ bunble
After the gem installation is complete, run the following command.
$ rails g rspec:install
This completes the installation of RSpec itself. It's easy.
Next, we will configure the settings for Capybara to be used in RSpec.
spec/spec/helper.rb
require 'capybara/rspec'
RSpec.configure do |config|
config.before(:each, type: :system) do
config.include Capybara::DSL
config.include FactoryBot::Syntax::Methods
driven_by :selenium_chrome_headless
end
This time, I will use Headless Chrome as the browser with system spec, so I set selenium_chrome_headless.
To install FactoryBot, describe it in the Gemfile as follows.
Gemfile.
gem 'factory_bot_rails'
$ bundle
This completes the introduction of FactoryBot.
Next, I would like to touch on how to write RSpec, but it seems to be long, so I will do it next time.
The content is simple in the first post, but I hope you will read it again next time.
Recommended Posts