LoginSignup
13
5

More than 5 years have passed since last update.

【RSpec】で書く「Rails Tutorial 5章」のテスト

Last updated at Posted at 2018-10-18



こんにちは。

現在、RSpec猛勉強中のGoiと言います。

先に言っておくと、
こちらの記事は多分「クソ記事」に該当する可能性があるため、
マサカリを投げられる方はお引き取りください。


本題に入るのですが、
今現在ダメもとでRails TutorialをRSpecで進めるという暴挙に出ています。

  • 前提条件

・Viewのトップページ(Home)より、各リンク先にページ遷移できるかのテスト
・homeがトップページ(root_path)
・リンク先に遷移するために押下文字がclick_linkに該当
have_content("XXX")のXXXに入る文字列は、ページ遷移先に表示されるコンテンツのこと
  ※home(トップページ)だと、「Welcom to the Sample App」や「This is the home page...」のコンテンツ(文字に該当)

スクリーンショット 2018-10-18 20.52.06.png



実際にfeatureスペックを使用したテストが下記になります。

Feature(エンドツーエンド)テスト

spec/features/homes_spec.rb
require 'rails_helper'

RSpec.feature "Homes", type: :feature do

  scenario "homeへページ遷移できるか" do
    visit root_path
    click_link "Home"

    expect(page).to have_content("Welcome to the Sample App")
  end

  scenario "aboutへページ遷移できるか" do
    visit root_path
    click_link "About"

    expect(page).to have_content("Help Log in About")
  end

  scenario "helpへページ遷移できるか" do
    visit root_path
    click_link "Help"

    expect(page).to have_content("Log in Help")
  end

  scenario "contactへページ遷移できるか" do
    visit root_path
    click_link "Contact"

    expect(page).to have_content("Help Log in Contact")
  end

  scenario "Sign upへページ遷移できるか" do
    visit root_path
    click_on "Sign up now!"

    expect(page).to have_content("Sign up")
  end
end


ユニットテスト = controller spec
インテグレーションテスト = request spec
エンドツーエンドテスト = feature spec / system spec

上記の通り、テストにはそれぞれ種類があり、
上で書いたfeature(エンドツーエンド)テストを書くまえにrequest(インテグレーション)テストを書くべきとご指摘いただきました。

そのため、改めてrequestテストを書いてみました。

Request(インテグレーション)テスト

spec/requests/homes_api_spec.rb
require 'rails_helper'

RSpec.describe "HomesApi", type: :request do
  describe "GET path check" do
    it "Homeページのhttpリクエストは正しいか" do
      get root_path
      expect(response).to have_http_status(200)
    end

    it "Aboutページのhttpリクエストは正しいか" do
      get about_path
      expect(response).to have_http_status(200)
    end

    it "Helpページのhttpリクエストは正しいか" do
      get help_path
      expect(response).to have_http_status(200)
    end

    it "Contactページのhttpリクエストは正しいか" do
      get contact_path
      expect(response).to have_http_status(200)
    end

    it "User/newページのhttpリクエストは正しいか" do
      get sign_up_path
      expect(response).to have_http_status(200)
    end
  end
end



初めて自分で一から作ったテストのため
簡素であり見応えのないものとなっています。

こちらで一応テストは成功します。

しかし、経験者の方からすればより良い記述方法やそもそもfeature使わなくていいとか
その他諸々のアドバイスありましたら教えていただけるとありがたいです。


<追記>
@juchito さん(everydayrailsの著者)より、
コメントの通り今後のエンドツーエンドテストだと
feature specではなくsystem specの勉強をした方が良いとのアドバイスをいただきました。

まだsystem specを試せていませんので
改めて試し次第、こちらの記事も更新したいと思います。


変更履歴
10/19
・feature spec修正
・request spec追加
・各テストと各specの繋がりを記述
・<追記>部分を追加

13
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5