문제

I'm doing a code that need to search a external API, but during development I haven't access to this API, so my current solution to run the server and navigate through the system is:

def api_call
   return { fake: 'This is a fake return' } if Rails.env.development?

   # api interaction code
   # ...
end

This let my code dirt, so my question is: There are a pattern (or a better way) to do this?

도움이 되었습니까?

해결책

The pattern I use is to replace api object with one that fakes all methods when in development.

class Api
  def query
    # perform api query
  end
end

class FakeApi
  def query
    { fake: 'This is a fake return' }
  end
end

# config/environments/production.rb
config.api = Api.new

# config/environments/test.rb
# config/environments/development.rb
config.api = FakeApi.new

# then

def api_call
  Rails.configuration.api.query # no branching here! code is clean
end

Basically, you have two classes, Api which does real work and FakeApi that returns pre-baked faked responses. You then use Rails' environment configuration to set different apis in different environments. This way, your client code (that calls #query) doesn't have to care about current environment.

다른 팁

Webmock (https://github.com/bblimke/webmock) is generally accepted as the best gem to stub out external services, and has the added benefit of letting you test how your api_call method parses the API's response.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top