[Ruby on Rails] View test with RSpec

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

We will proceed on the premise that this is done. [Ruby on Rails] Until RSpec is introduced

Click here to test the model [Ruby on Rails] Model test with RSpec

Click here to test the controller [Ruby on Rails] Controller test with RSpec

view test preparation

・ Creating a file

① Create system folder and factories folder under spec. In the system folder, also create the view file you want to test and Create a model of dummy data in the factories folder.

This time to test the view of the post The file structure is as follows.

spec/system/post_spec.rb
→ Describe the content you want to test.

spec/factories/post.rb
spec/factories/user.rb
→ Create dummy data.

② Enables Factory Bot. It is convenient to use it because you can register the DB and build the model like user = create (: user). Create a support folder and factory_bot.rb file under spec and describe as follows.

spec/support/factory_bot.rb


RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Then add the following:

spec/rails_helper.rb


# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot' #<-Addition

...

Editing spec_helper.rb

RSpec the following content.configure do |config|Add in.

spec/spec_helper.rb


RSpec.configure do |config|
  config.before(:each, type: :system) do
    driven_by :rack_test
  end

...

end

Actual code

First, create dummy data.

spec/factories/user.rb


FactoryBot.define do
  factory :user do
    email { Faker::Internet.email }
    phone_number { 12345678909 }
    password { 'password' }
    password_confirmation { 'password' }
  end
end

spec/factories/post.rb


FactoryBot.define do
  factory :post do
    body { Faker::Lorem.characters(number:20) }
    user
  end
end

Next, write the test code.

spec/system/post_spec.rb


require 'rails_helper'

describe 'Post test' do
  let(:user) { create(:user) }
  let(:user2) { create(:user) }
  let(:post) { create(:post, user: user) }
  let(:post2) { create(:post, user: user2) }
  before do
    visit new_user_session_path
    fill_in 'user[email]', with: user.email
    fill_in 'user[password]', with: user.password
    click_button 'Login'
    visit user_posts_path(user, post)
  end
  describe 'Display test' do
    context 'New post screen' do
      before do
        visit new_user_post_path(user, post)
      end
      it 'body form is displayed' do
        expect(page).to have_field 'post[body]'
      end
      it 'New post button is displayed' do
        expect(page).to have_button 'New post'
      end
    end
  end
  describe 'Editing test' do
    context 'Transition to the edit screen of your post' do
      it 'Can transition' do
        visit edit_user_post_path(user, post)
        expect(current_path).to eq('/users/' + user.id.to_s + '/posts/' + post.id.to_s + '/edit')
      end
    end
    context 'Transition to the edit screen of another person's post' do
      it 'Cannot transition' do
        visit edit_user_post_path(user, post2)
        expect(current_path).to eq('/users/' + user.id.to_s + '/posts')
      end
    end
  end
end

Then do the following in your terminal:

Terminal


$ rspec spec/requests

If you get an error, please try this as well

Terminal


$ bundle exec rspec spec/system --format documentation

If you pass the test

Finished in 3.64 seconds (files took 2.75 seconds to load)
4 examples, 0 failures

Since it is displayed like this, it means that the test content is correct.

Reference (excerpt from model test)

[Ruby on Rails] Model test with RSpec On the contrary, if it does not pass the test, you can see where the error is occurring in this way, so You will be able to see if the test code is wrong, the validation is wrong, and so on.

Failures:

  1)Post model test Validation test title column Must be 20 characters or less
     Failure/Error: let!(:post) { build(:post) }

     NoMethodError:
       undefined method `build' for #<RSpec::ExampleGroups::Post::Nested::Title:0x000000000619e938>
     # ./spec/models/post_spec.rb:9:in `block (3 levels) in <top (required)>'

  2)Post model test Validation test title column Must not be blank
     Failure/Error: let!(:post) { build(:post) }

     NoMethodError:
       undefined method `build' for #<RSpec::ExampleGroups::Post::Nested::Title:0x0000000007491518>
     # ./spec/models/post_spec.rb:9:in `block (3 levels) in <top (required)>'
Finished in 0.07992 seconds (files took 2.41 seconds to load)
2 examples, 2 failures

Failed examples:

rspec ./spec/models/post_spec.rb:11 #Post model test Validation test title column Must be 20 characters or less
rspec ./spec/models/post_spec.rb:15 #Post model test Validation test title column Must not be blank

Also, using rspec ./spec/models/post_spec.rb:11 at the bottom, You can also check the test contents individually as shown below.

Terminal


$ rspec spec/models/post_spec.rb:11

Summary

This time First, create dummy data and After actually logging in on the login screen,

  1. Go to the posting screen while logged in and see if the display is correct. 2, Is it possible to transition to the posting screen of another person? I tested these two points.

Because there is also a way to test javascript If you are interested, please check it out.

Also, on twitter, technologies and ideas that have not been uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork

Recommended Posts

[Ruby on Rails] View test with RSpec
[Ruby on Rails] Controller test with RSpec
[Ruby on Rails] Model test with RSpec
[Rails] Test with RSpec
Introducing Rspec with Ruby on Rails x Docker
Understand code coverage with Rspec, the Ruby on Rails test framework
Introducing Rspec, a Ruby on Rails test framework
Run Ruby on Rails RSpec tests with GitHub Actions
Let's unit test with [rails] Rspec!
Notes on using FCM with Ruby on Rails
Test run on rails
Ruby on Rails Elementary
Ruby on Rails basics
Test Nokogiri with Rspec.
Ruby On Rails Association
I rewrote the Rails tutorial test with RSpec
Publish the app made with ruby on rails
[Rails] Procedure for linking databases with Ruby On Rails
Determine the current page with Ruby on Rails
[Ruby on Rails] Upload multiple images with refile
I made a portfolio with Ruby On Rails
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Delete s3 images with Active Strage
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Ruby on Rails basic learning ①
Test Active Strage with RSpec
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
[Rails] Test code using Rspec
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
[Ruby On Rails] Error in test using RSpec MySQL client is not connected
Commentary on partial! --Ruby on Rails
Test GraphQL resolver with rspec
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
[Rails] About Rspec response test
Ruby on rails learning record -2020.10.06
Ruby on Rails validation summary
Created RSS / Atom format sitemap with Ruby on Rails
Ruby on Rails Basic Memorandum
I tried installing Ruby on Rails related plugin with vim-plug
[Ruby on Rails] Add a column with a foreign key constraint
[Ruby on Rails] Implement login function by add_token_to_users with API
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
Apply CSS to a specific View in Ruby on Rails
Ruby on Rails Overview (Beginner Summary)
[Ruby on Rails] Read try (: [],: key)
[Ruby on Rails] yarn install --check-files
Ruby on Rails variable, constant summary
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
[Ruby on Rails] Introduced paging function
Basic knowledge of Ruby on Rails
Progate Ruby on Rails5 Looking Back
Test with RSpec + Capybara + selenium + chromedriver
How to use Ruby on Rails
[Ruby on Rails] Add / Remove Columns