Search code examples
ruby-on-railsrubyrspecrequesthttparty

How to retreive host url in development and production in Rails/Rspec?


I'm creating tests for my senders_controller and am trying to retrieve my base url to be able to call an HTTParty request. I basically need the same method to be able to retrieve me one of these two links depending on the environment:

  • in development: http://localhost:3100/senders
  • in production: https://example.com/senders

My tests work in my spec/senders_controller.rb like this:

HTTParty.post("http://localhost:3100/senders", query: {email: user.email})

But I want that link to also work in production, which is why I'm looking for a dynamic way to get the base url in both development and production.

Any ideas?


Solution

  • An option that I have used in the past is to use the config gem.

    You can create variables for different environments and then just call that variable.

    For example, you can have a config/settings/development.yml that defines the url one way:

    base_url: "http://localhost:3100/senders"

    And a config/settings/production.yml file that defines it another:

    base_url: "https://example.com/senders"

    Then call it with Settings.base_url

    It automatically resolves the environment and populates the correct settings for that environment.