技術系ブログ

とにかく小ネタで

【rails5.2】deviseを用いた、twitterログイン機能導入からherokuでの本番環境利用まで Rspec編

Rspecでテストするのも残しておきます。
参考:🍺RSpecでOmniAuthのFacebookログイン/サインアップのFeatureテストを書く - Qiita
これのtwitter版を書けばいいだけです。

モックを作成するときにspec/supportに書くのですが 参考:RSpec3でspec/support内のファイルを読み込む - Qiita

しっかり上記のようにコメントアウトしないといけません。

 #spec/rails_helper.rb

Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
...............
RSpec.configure do |config|
..............
  OmniAuth.config.test_mode = true
  config.include OmniauthMocks
end

touch spec/support/omniauth_mocks.rb

#spec/support/omniauth_mocks.rb

# frozen_string_literal: true

module OmniauthMocks
  def twitter_mock
    OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({
      :provider => "twitter",
      :uid => "123456",
      :info => {
        :nickname => "johnqpublic",
        :name => "John Q Public",
        :location => "Anytown, USA",
        # :image => "http://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
        :description => "a very normal guy.",
        :urls => {
          :Website => nil,
          :Twitter => "https://twitter.com/johnqpublic"
        }
      },
      :credentials => {
        :token => "a1b2c3d4...",
        :secret => "abcdef1234"
      },
      :extra => {
        # :access_token => "", # An OAuth::AccessToken object
        :raw_info => {
          :name => "John Q Public",
          :listed_count => 0,
          :profile_sidebar_border_color => "181A1E",
          :url => nil,
          :lang => "en",
          :statuses_count => 129,
          :profile_image_url => "http://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
          :profile_background_image_url_https => "https://twimg0-a.akamaihd.net/profile_background_images/229171796/pattern_036.gif",
          :location => "Anytown, USA",
          :time_zone => "Chicago",
          :follow_request_sent => false,
          :id => 123456,
          :profile_background_tile => true,
          :profile_sidebar_fill_color => "666666",
          :followers_count => 1,
          :default_profile_image => false,
          :screen_name => "",
          :following => false,
          :utc_offset => -3600,
          :verified => false,
          :favourites_count => 0,
          :profile_background_color => "1A1B1F",
          :is_translator => false,
          :friends_count => 1,
          :notifications => false,
          :geo_enabled => true,
          :profile_background_image_url => "http://twimg0-a.akamaihd.net/profile_background_images/229171796/pattern_036.gif",
          :protected => false,
          :description => "a very normal guy.",
          :profile_link_color => "2FC2EF",
          :created_at => "Thu Jul 4 00:00:00 +0000 2013",
          :id_str => "123456",
          :profile_image_url_https => "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
          :default_profile => false,
          :profile_use_background_image => false,
          :entities => {
            :description => {
              :urls => []
            }
          },
          :profile_text_color => "666666",
          :contributors_enabled => false
        }
      }
    }
  )
  end
end 

参考:GitHub - arunagw/omniauth-twitter: OmniAuth strategy for Twitter

文字列をfreezeさせるいくつかの方法 - Qiita

【OmniAuth + Devise】Twitterのログイン認証をテストする方法【Rspec】 - Qiita

これはrequest.env['omniauth.auth']の中身をテスト環境で使うためです。

最後に touch spec/system/omniauth_spec.rb

#spec/system/omniauth_spec.rb

require "rails_helper"

describe "twitter機能", type: :system do
  before do
    Rails.application.env_config["omniauth.auth"] = twitter_mock
    visit new_user_session_path
  end
  it "twitter連携でサインアップ成功" do
    expect{
      click_link "twitterでログイン"
    }.to change(User, :count).by(1)
    expect(page).to have_content "ログインしました。"
  end
end