0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails,Rspec】deviseによる認証機構のテストを書こうと思う。

Last updated at Posted at 2022-11-03

rspecの設定

deviseによる認証機構について、とりあえず手始めに、model specを書いていこうと思う。
まずRSpecを導入するために以下の通りgemをinstallする。(今回、開発環境にはdockerを使用している)

Gemfile
  gem 'rspec-rails'
  gem "factory_bot_rails"
terminal
$ docker-compose exec app bundle install
terminal
$ docker-compose exec app bundle exec rails g rspec:install

rails_helper.rb の追記

spec/rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'capybara/rspec'
require'devise'
require File.expand_path("spec/support/controller_macros.rb")
# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  abort e.to_s.strip
end
RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # You can uncomment this line to turn off ActiveRecord support entirely.
  # config.use_active_record = false

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, type: :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!

  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include Devise::Test::IntegrationHelpers, type: :request
  config.extend ControllerMacros, :type => :controller
  config.include FactoryBot::Syntax::Methods
end

テストデータ

今回はdeviseによる認証機構を、IDとパスワードによる認証に改造してあるので、以下のよう記述となる。

spec/factories/user.rb
FactoryBot.define do
  factory :user do
    user_id               {"1212121212"}
    password              {"111111"}
    password_confirmation {"111111"}
  end
end

controller_macros.rbの記述

spec/macros/controller_macros.rb
module ControllerMacros
  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in FactoryBot.create(:admin) # Using factory bot as an example
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryBot.create(:user)
      user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
      sign_in user
    end
  end
end

テストの記述

spec/models/user_spec.rb
equire 'rails_helper'

RSpec.describe User, type: :model do
  describe 'ユーザー登録' do
    it "user_id、passwordとpassword_confirmationが存在すれば登録できること" do
      user = build(:user)
      expect(user).to be_valid  # user.valid? が true になればパスする
    end
  end
end

DBの設定

テストを実行するに際して、ここではテスト用のDBコンテナを作成しておく。
docker-compose.ymlにテスト用のDBを作成する。あくまで一例であるが以下のように追記を行う。
ポートマッピングにおけるローカルのポート番号については、mysqlのデフォルトのポート番号が3306番ポートであり、これは開発環境のDBがすでに使っているので、テスト環境では別のポート番号をしてする。(今回は3300番ポートを指定している)

docker-compose.yml
・・・・

db-test:
    image: mysql:5.7
    ports:
      - 3300:3306
      #このローカルのポート番号(左側のポート番号)は3306以外(開発環境のDBのポート番号以外)を指定する。
    expose:
      - 3306
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: app_name_test
    volumes:
      - db-data:/var/lib/mysql

・・・・

その後コンテナをbuildし直す。

terminal
$ docker-compose down
$ docker-comose build
$ docker-compose up -d

またテスト用のDBについてcreateとmigrateを実行する。

terminal
$ docker-compose exec app rails db:create RAILS_ENV=test
$ docker-compose exec app rails db:migrate RAILS_ENV=test

その後、晴れてRspecによるテストを実行する。

terminal
docker-compose exec app bundle exec rspec
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?