LoginSignup
1
2

More than 3 years have passed since last update.

Capybaraを使う!!!(Rails + Rspec + Capybara)

Last updated at Posted at 2020-04-17

Rspecの導入がまだの方はこちら

Rails + Rspec + Capybaraを前提として進めていきます。

Capybara

テストのためのrubyフレームワークです
これを使うと画面表と同じ様な感覚でE2Eテストを実施できます。

インストールする

1.Gemfileに追加

Gemfile
group :development, :test do
 gem 'capybara'
 gem 'selenium-webdriver'
end

インストールします、

$ bundle install

2.spec_helper.rbにrequire 'capybara/rspec'を追加

spec_helper.rb
require 'capybara/rspec'
RSpec.configure do |config|

3.テストを書く

スクリーンショット 2020-04-17 17.23.05.png
のような
一般的なログイン画面で
メールアドレス(name="email"),
パスワード(name="password")
でログイン(ログインを押したら"ログインしました")
するまでのテストです。

spec/system/user_spec.rb
require 'rails_helper'

RSpec.feature 'login' do
  background do
    # ユーザ作成
    User.create!(name:'testuser', email: 'foo@example.com', password: '123456', password_confirmation: '123456')
  end
  scenario 'ログインする' do
    # ログインページを開く
    visit login_path

    # ログインフォームにメールアドレスとパスワードを入力する
    fill_in 'email', with: 'foo@example.com'
    fill_in 'password', with: '123456'
    # ログインボタンをクリック
    click_on 'ログイン'
    # ログインに成功したことを検証
    expect(page).to have_content 'ログインしました'
  end
end

画面上のような操作でテストができるので便利です!!!

※RSpecでヘルパーを作成する方法
こちらの記事が参考になります
https://breakthrough-tech.yuta-u.com/rspec/how-to-make-spec-support/

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