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