・ Devise is introduced ・ About the contents of the test written this time -If the user is logged in, it should be displayed correctly.
app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action: authenticate_user!
def index
@posts = Post.all
end
end
① Create requests and factories folders under spec
-Create spec/requests/posts_request.rb → File that describes the contents of the test
・ Spec/factories/user.rb ・ Create spec/factories/post.rb → File to create dummy data about user and post
(2) Create a support folder and factory_bot.rb file under spec so that FactoryBot can be used.
spec/support/factroy_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Method #For FactoryBot
config.include Devise::Test::IntegrationHelper, type: :request #devise sign_in method becomes available
end
Then edit rails_helper.rb
spec/rails_helper.rb
require 'spec_helper'
...
require 'rspec/rails'
require 'support/factroy_bot' #← This description allows you to use FactroyBot
spec/factories/user.rb
FactoryBot.define do
factory :user do
email { Faker::Internet.email }
name { "testuser1" }
password { "password" }
password_confirmation { "password" }
end
end
spec/factories/post.rb
FactroyBot.defind do
factory :post do
body { Faker::Lorem.charactors(number: 15) } #Create a 15-character dummy statement
end
end
spec/requests/post_spec.rb
require 'rails_helper'
RSpec.describe 'post_controller test', type: :request do
let(:user) { create(:user) }
let(:post) { create(:post) }
describe 'If you are logged in' do
before do
sign_in user
get posts_path
end
it 'Requests to the post list page should be 200 ok' do
expect(response.status).to eq 200
end
it 'The page title is displayed correctly' do
expect(response.body).to include('Post list')
end
end
describe "If you are not logged in" do
before do
get posts_path
end
it 'The request will be 401' do
expect(response.status).to eq 401
end
it 'Title is not displayed' do
expect(response.body).to_not include("Post list")
end
end
end
All you have to do is run RSpec!
$ rspec spec/requests
Since this is a beginner's article, I think there are ninety-nine mistakes. If anyone notices it, I would be very grateful if you could let me know! !
Recommended Posts