Skip to content

Instantly share code, notes, and snippets.

@jruusu
Created September 27, 2016 14:41
Show Gist options
  • Save jruusu/bf03340764e05270317ff4e5ef3e0ab9 to your computer and use it in GitHub Desktop.
Save jruusu/bf03340764e05270317ff4e5ef3e0ab9 to your computer and use it in GitHub Desktop.
Service stubbing in Rails

Example: stubbing a service object in a Rails application

app/models/services/sharepoint.rb (partial):

module SharePoint

  # Live SharePoint Context class, uses OAuth2 and RestClient
  # to talk to the outside world
  class LiveContext

    # Returns current authenticated SharePoint::User
    def current_user
      User.from_xml(
        self,
        rest_api['SP.UserProfiles.PeopleManager/GetMyProperties?$select=AccountName'].get
      )
    end

  end

  # Stub SharePoint Context class, provides canned responses
  # without calling remote web services 
  class StubContext < LiveContext

    def current_user
      User.new(self, 'stub account name')
    end

  end

  # Choose Context implementation based on application config, if any.
  # Default is Live.
  # Available to the app as SharePoint::Context
  Context = (
    APP_CONFIG[:test_doubles][:sharepoint_context] || 'SharePoint::LiveContext'
  ).constantize

end

config/app_config.yml (partial):

# Application configuration settings
defaults: &defaults
  test_doubles: {}

development:
  <<: *defaults

test:
  <<: *defaults
  test_doubles:
    sharepoint_context: SharePoint::StubContext

production:
  <<: *defaults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment