Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create fake behavior for external call in development environment

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?

like image 330
daniloisr Avatar asked Mar 04 '26 12:03

daniloisr


1 Answers

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.

like image 188
Sergio Tulentsev Avatar answered Mar 06 '26 02:03

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!