LoginSignup
0
1

More than 3 years have passed since last update.

【これを知りたかった】Docker+RailsでRSpec導入〜トップページ表示確認テストの書き方まで

Last updated at Posted at 2021-01-11

背景

  • Railsのポートフォリオ作成で、RSpecの導入を検討
  • 導入から、トップページの表示を確認するテストの書き方までをまとめました

1. Gemのインストール

GemfileにRails用のrspecとfactory_botのgemを加える

Gemfile
group :development, :test do
  gem "rspec-rails"
  gem "factory_bot_rails"
end

Dockerでbuildし直す

docker-compose build

2. rspecの導入

以下のコマンドでRailsアプリに、rspecを導入

$ bundle exec rails generate rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb

3. rspecの生成ファイルの定義

  • 設定ファイルはconfig/application.rb
  • falseをつけると不要なテストファイルは作成されなくなる
config/application.rb
config.generators do |g|
  g.test_framework :rspec, 
        # 不要なテストファイルは以下のようにfalseをつけて書く
        view_specs: false, 
        helper_specs: false, 
        controller_specs: false, 
        routing_specs: false
end

4. Viewをテストしてみる

Viewテスト用のrspec作成

rails g rspec:view Homes

ただ、これだけだと/spec/views/homes/というフォルダしか作成されない

テスト用のファイル作成

/spec/views/homes/以下にindex.html.erb_spec.rbを作成し、以下を記述

/spec/views/homes/index.html.erb_spec.rb
require 'rails_helper'

RSpec.describe "homes/index", type: :view do
  it 'should display top page' do
    visit "/"
    expect(page).to have_content 'こされ'
  end
end

以下補足
* visit "/" : ルートに遷移
* expect(page).to have_content '文字列' : 現在の表示ページ上に"文字列"があることを確認

テスト実行

$ rspec

homes/index
  should display top page

Finished in 24.64 seconds (files took 7.02 seconds to load)
1 example, 0 failures

0 failuresなので、テストが成功

RSpecで「NoMethodError: undefined method `visit' for ~ 」と怒られた時

spec/spec_helper.rb
...

require 'capybara/rspec'

RSpec.configure do |config|
  config.include Capybara::DSL # 追記

...

参考

0
1
0

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
0
1