[I wanted to know this] Introducing RSpec with Docker + Rails-How to write a top page display confirmation test

background

1. Install Gem

Add rspec for Rails and factory_bot gem to Gemfile

Gemfile


group :development, :test do
  gem "rspec-rails"
  gem "factory_bot_rails"
end

Rebuild with Docker

docker-compose build

2. Introduction of rspec

Introduce rspec to Rails app with the following command

$ bundle exec rails generate rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

3. Definition of rspec generation file

config/application.rb


config.generators do |g|
  g.test_framework :rspec, 
        #Write unnecessary test files with false as shown below
        view_specs: false, 
        helper_specs: false, 
        controller_specs: false, 
        routing_specs: false
end

4. Test View

Create rspec for View test

rails g rspec:view Homes

However, with this alone, only the folder /spec/views/homes/ will be created.

File creation for testing

Create index.html.erb_spec.rb under /spec/views/homes/ and write the following

ruby:/spec/views/homes/index.html.erb_spec.rb


require 'rails_helper'

RSpec.describe "homes/index", type: :view do
  it 'should display top page' do
    visit "/"
    expect(page).to have_content 'Strained'
  end
end

The following supplement

Test run

$ rspec

homes/index
  should display top page

Finished in 24.64 seconds (files took 7.02 seconds to load)
1 example, 0 failures

0 failures, so the test succeeded

When RSpec gets angry with "No Method Error: undefined method` visit'for ~ "

spec/spec_helper.rb


...Abbreviation

require 'capybara/rspec'

RSpec.configure do |config|
  config.include Capybara::DSL #Postscript

...Abbreviation

reference

Recommended Posts

[I wanted to know this] Introducing RSpec with Docker + Rails-How to write a top page display confirmation test
I want to write a unit test!
I want to test Action Cable with RSpec test
How to test a private method with RSpec for yourself
I tried to create a padrino development environment with Docker
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
[RSpec] How to write test code
I wanted to implement a slide show in a fashionable way with slick.
[Rspec] Flow from introducing Rspec to writing unit test code for a model
I want to display a PDF in Chinese (Korean) with thin reports
After all I wanted to preview the contents of mysql with Docker ...