LoginSignup
2
3

More than 3 years have passed since last update.

Rails Tutorialの知識から【ポートフォリオ】を作って勉強する話 #4 System spec導入編

Last updated at Posted at 2019-08-07

こんな人におすすめ

  • プログラミング初心者でポートフォリオの作り方が分からない
  • Rails Tutorialをやってみたが理解することが難しい

前回:#3 Bootstrap4, jQueryプラグイン導入編
次回:#5 Userモデル編

今回の流れ

  1. 完成のイメージを理解する
  2. System specを導入する
  3. トップページのブラウザテストを書く

※ この記事は、ポートフォリオを作る理由をweb系自社開発企業に転職するためとします。
※ 2020年3月30日、記事を大幅に更新しました。

完成のイメージを理解する

#3では、トップページを仕上げました。
今回は、トップページのブラウザテストを行います。
その際、System specを使うのでいくつか設定を変更します。
設定後、ブラウザテストの処理を書きます。

以上です。

System specを導入する

#2でちらっと紹介した、System specを導入します。
はじめに、必要なGemを追加します。

Gemfile
group :test do
  gem 'capybara', '>= 2.15'
- gem 'selenium-webdriver'
- gem 'chromedriver-helper'
+ gem 'webdrivers'
end
shell
$ bundle install

古い記事では、chromedriver-helperを追加するように書かれています。
しかしchromedriver-helperがサポート終了のため、webdriversを使います。
webdriversを使う際、selenium-webdriverも不要です。

次に、RSpecの設定を変更します。
これにより、ブラウザテストが機能します。

spec/rails_helper.rb
# 中略
RSpec.configure do |config|
# 中略
# 一番下の直前に追加
  config.before(:each) do |example|
    if example.metadata[:type] == :system
      driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400]
    end
  end
end

参考になりました↓
サポートが終了したchromedriver-helperからwebdrivers gemに移行する手順
【Rails】『RSpec + FactoryBot + Capybara + Webdrivers』の導入&初期設定からテストの書き方まで
rspec-rails 3.7の新機能!System Specを使ってみた

トップページのブラウザテストを書く

Rails Tutorial 5.3.4 リンクのテストにならって、テストを作ります。
まずはファイルを作ります。ジェネレーターがないので手動で作ります。

shell
$ mkdir ./spec/systems/
$ touch ./spec/systems/site_layout_spec.rb

テストする内容は以下の通りです。

  • ロゴ画像とロゴテキストに、root_pathのリンクが2つある
  • Loginボタンに、login_pathのリンクが1つある

ポートフォリオのトップページについては#3をご覧ください。
Rails Tutorialとの差分も載せておきます。
(一部改変)

spec/systems/site_layout_spec.rb(RSpec:ポートフォリオ)
require 'rails_helper'

RSpec.describe "SiteLayouts", type: :system do  
  describe "home layout" do    
    it "contains root link" do
      visit root_path
      expect(page).to have_link nil, href: root_path, count: 2
    end

    it "contains login link" do
      visit root_path
      expect(page).to have_link 'Login', href: login_path
    end
    # 中略
  end
end
test/integration/site_layout_test.rb(Minitest:Tutorial)
require 'test_helper'

class SiteLayoutTest < ActionDispatch::IntegrationTest

  test "layout links" do
    get root_path
    assert_template 'static_pages/home'
    assert_select "a[href=?]", root_path, count: 2
    assert_select "a[href=?]", login_path
  end
end

System specの構文がわからない方はこちらをご覧ください↓
使えるRSpec入門・その4「どんなブラウザ操作も自由自在!逆引きCapybara大辞典」

コードの記述は以上です。あとはテストを走らせます。
テストを走らせるには、以下のようにします。

shell
$ rails spec

無事テストが成功したら、今回は以上です。


前回:#3 Bootstrap4, jQueryプラグイン導入編
次回:#5 Userモデル編

2
3
1

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
2
3