2014年3月14日金曜日

rails4 twitterでログイン認証 その2

rails4でtwitterログイン認証を扱ったのでメモ。前回の続き

環境

  • rails(ruby2.1.0, rails4.0.3)
  • twitterのdeveloper登録済み
  • mongoDB

前回は、pathまで設定したので、今回はmongoDB周りの整備をする
まずは、mongoDBをrsepecでテストするための設定を行う

spec_helper.rbに以下を記述


  # 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 = false

  # Database Cleaner
  config.before(:suite) do
    DatabaseCleaner[:mongoid].strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner[:mongoid].start
  end

  config.after(:each) do
    DatabaseCleaner[:mongoid].clean
  end

上記のコードにはDatabaseCleanerのgemが必要なので、installしていない場合は以下のようにGemfileに記載してbundle updateを行うこと


group :test do
  gem "database_cleaner", ">= 0.9.1"
  gem "email_spec", ">= 1.4.0"
end

モデルの作成。providerとuidは必須。monogoDBなので、時間はtime型を使用


rails g mongoid:model user provider:string uid:string 
name:string nickname:string email:string image:string 
created_at:time updated_at:time deleted_at:time

sessionコントローラーにcreate, failure, destroyメソッドを記述


  # twitter login first
  def create
   auth = request.env["omniauth.auth"]
   user = User.where(:provider => auth['provider'], :uid => auth['uid']).first
          || User.create_with_omniauth(auth)
   if user
     session[:user_id] = user.id
     redirect_to :controller => 'topic', :action => 'index'
   else
     render :index
   end
  end

  # twitter login failure
  def failure
   render :index, :alert => "Authentication error"
  end

  # sign out
  def destroy
    reset_session
    render :index, :notice => 'Signed out!'
  end

rspec用のテストを用意。ファイル名はspec/controllers/session_controller_spec.rb


  describe "GET create" do

    before do
      request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:twitter]
    end

    it "should successfully create a user" do
      expect {
        post :create, provider: :twitter
      }.to change{ User.count }.by(1)
    end

    it "should successfully create a session" do
      session[:user_id].should be_nil
      post :create, provider: :twitter
      session[:user_id].should_not be_nil
    end

    it "should redirect the user to the topic/index" do
      post :create, provider: :twitter
      response.should redirect_to(:controller => 'topic', :action => 'index')
    end

  end

  describe "GET failure" do
    it "should render the index template" do
      get :failure
      response.should render_template("index")
    end
  end

  describe "GET destroy" do

    before do
      request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:twitter]
      post :create, provider: :twitter
    end
 
    it "should clear the session" do
      session[:user_id].should_not be_nil
      delete :destroy
      session[:user_id].should be_nil
    end
 
    it "should redirect to the index page" do
      delete :destroy
      response.should render_template("index")
    end
  end


mock_auth[:twitter]で利用しているモックをspec_helper.rbに記載


# OmniAuth Mock Test Data
OmniAuth.config.test_mode = true
omniauth_hash = { 'provider' => 'twitter',
                  'uid' => '12345',
                  'info' => {
                      'name' => 'taro',
                      'email' => 'taro@taro.com',
                      'nickname' => 'jptaro'
                  }
}

OmniAuth.config.add_mock(:twitter, omniauth_hash)

テスト実行


rake spec

エラーなしで実行できるはずです。これで完了です。

twitter認証をRspecでテストするのはあまり見かけないので、実際にやっている人は少ないのかもしれませんね。シンプルなログイン操作なら必要ないかも。


参考サイト

この記事がお役にたちましたらシェアをお願いします

このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...