如何在 Rails/Rspec 的开发和生产中检索主机 url?
How to retreive host url in development and production in Rails/Rspec?
我正在为我的 senders_controller
创建测试并试图检索我的基础 url 以便能够调用 HTTParty 请求。我基本上需要相同的方法才能根据环境检索这两个 link 之一:
- 开发中:
http://localhost:3100/senders
- 生产中:
https://example.com/senders
我的测试在我的 spec/senders_controller.rb
中是这样工作的:
HTTParty.post("http://localhost:3100/senders", query: {email: user.email})
但我希望 link 也能在生产中使用,这就是为什么我正在寻找一种动态的方法来在开发和生产中获得基础 url。
有什么想法吗?
试试这个,简单又好用:
url = Rails.env.development? ? "localhost:3100/senders" : "example.com/senders"
HTTParty.post(url, query: {email: user.email})
我过去使用的一个选项是使用 config gem.
您可以为不同的环境创建变量,然后调用该变量。
例如,您可以使用 config/settings/development.yml
以一种方式定义 url:
base_url: "http://localhost:3100/senders"
还有一个 config/settings/production.yml
定义它的文件:
base_url: "https://example.com/senders"
然后用Settings.base_url
调用
它会自动解析环境并为该环境填充正确的设置。
我正在为我的 senders_controller
创建测试并试图检索我的基础 url 以便能够调用 HTTParty 请求。我基本上需要相同的方法才能根据环境检索这两个 link 之一:
- 开发中:
http://localhost:3100/senders
- 生产中:
https://example.com/senders
我的测试在我的 spec/senders_controller.rb
中是这样工作的:
HTTParty.post("http://localhost:3100/senders", query: {email: user.email})
但我希望 link 也能在生产中使用,这就是为什么我正在寻找一种动态的方法来在开发和生产中获得基础 url。
有什么想法吗?
试试这个,简单又好用:
url = Rails.env.development? ? "localhost:3100/senders" : "example.com/senders"
HTTParty.post(url, query: {email: user.email})
我过去使用的一个选项是使用 config gem.
您可以为不同的环境创建变量,然后调用该变量。
例如,您可以使用 config/settings/development.yml
以一种方式定义 url:
base_url: "http://localhost:3100/senders"
还有一个 config/settings/production.yml
定义它的文件:
base_url: "https://example.com/senders"
然后用Settings.base_url
它会自动解析环境并为该环境填充正确的设置。