T
T
therhino2015-03-08 13:19:12
Ruby on Rails
therhino, 2015-03-08 13:19:12

How to refactor the controller to test?

There is a controller with a bunch of private methods. Tell me, how best to reorganize and test it?

require 'httparty'

class Api::V1::SessionsController < Api::V1::ApplicationController
  respond_to :json

  def signin
    if code = params[:code]
      access_token = get_access_token

      if access_token.present?
        user = get_existing_user_or_create_new
        respond_with user, status: :ok
      else
        respond_with error: 'Invalid code!', status: 401
      end
    else
      head :bad_request
    end
  end

  private

  def access_credentials
    HTTParty.get('https://oauth.vk.com/access_token', query: {
        client_id: Rails.application.secrets.vk_app_id,
        client_secret: Rails.application.secrets.vk_app_secret,
        code: code,
        redirect_uri: signin_api_sessions_url
    }).parsed_response
  end

  def get_access_token
    access_credentials["access_token"]
  end

  def get_existing_user_or_create_new
    user_id = access_credentials["user_id"]
    user = User.where(uid: user_id).first_or_initialize! do |u|

      user_response = HTTParty.get('https://api.vk.com/method/users.get', query: {
        user_ids: user_id,
        access_token: access_token
      }.parsed_response

      u.name = %Q(#{user_response['first_name']} #{user_response['last_name']})
      u.uid = user_id
    end

    expires_in = access_credentials["expires_in"]
    user.generate_auth_token!(expires_in)
  end
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2015-03-08
@viktorvsk

For starters, just bring everything into the model. Extract method для начала
Затем, если есть желание - сюда

D
dzivalli, 2015-03-10
@dzivalli

Толстые модели, тонкие контроллеры. Переноси всю бизнес логику в модели и там тестируй. Контроллеры в основном нужны чтобы получать данные и отдавать их вьюхам. Вроде это рельс уэй :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question