RailsチュートリアルのテストをRspecで書いてみた[第5章]
はじめに
今回はRspecの学習の一環として、RailsチュートリアルのテストをRspecで書いていきます。
至らない点があるかもしれませんが、その際はコメントにてご指摘をお願いします。
各種バージョン
Ruby 2.7.0
Rails 6.0.3.3
Rspec 3.9
Capybara 3.33.0
Factory_bot_rails 6.1.0
第5章
リスト5.28: StaticPagesで扱う新しい名前付きルートに対するテスト
spec/requests/static_pages_request_pec.rb require 'rails_helper' RSpec.describe "Staticpages", type: :request do let(:base_title) { 'Ruby on Rails Tutorial Sample App' } describe "GET /" do it "returns http success" do get "/" aggregate_failures do expect(response).to have_http_status(:success) expect(response.body).to include base_title expect(response.body).not_to include "| #{base_title}" end end end describe "GET /help" do it "returns http success" do get "/help" #<=変更 aggregate_failures do expect(response).to have_http_status(:success) expect(response.body).to include "Help | #{base_title}" end end end describe "GET /about" do it "returns http success" do get "/about" #<=変更 aggregate_failures do expect(response).to have_http_status(:success) expect(response.body).to include "About | #{base_title}" end end end describe "GET /contact" do it "returns http success" do get "/contact" #<=変更 aggregate_failures do expect(response).to have_http_status(:success) expect(response.body).to include "Contact | #{base_title}" end end end end
リスト5.32: レイアウトのリンクに対するテスト
spec/system/static_pages_spec.rb require 'rails_helper' RSpec.describe "StaticPages", type: :system do scenario "「/」 にアクセスした場合,タイトルは「Ruby on Rails Tutorial Sample App」です" do visit root_path aggregate_failures do expect(page.title).to eq "Ruby on Rails Tutorial Sample App" expect(page).to have_link 'Home', href: root_path expect(page).to have_link 'sample app', href: root_path expect(page).to have_link 'Help', href: help_path expect(page).to have_link 'About', href: about_path expect(page).to have_link 'Contact', href: contact_path expect(page).to have_link 'Sign up now!', href: signup_path end end end
<a>タグのURL先が正しいかを確認するテストだった為、「have_link」メソッドを使用しました。