如何使用来自heroku的编程当前主机并在rspec测试中使用它?

时间:2015-12-17 13:07:54

标签: ruby heroku rspec sinatra

我正在撰写一个简单的网络应用程序(sinatra)github authentication

我必须使用回调参数创建一个链接,例如:https://github.com/login/oauth/authorize?client_id=b5b1a33df1c7b5acccac&redirect_uri=http://localhost:4567/step2callback&scope=public_repo,user,gist,admin:repo_hook,gist,这样当用户点击它时,它将进行身份验证,授权我的应用程序,然后将用户发送回我的网络应用程序

由于我正在使用rspec,我想制作一个传递测试和生产的代码,所以我想让当前的主机+端口在我生成链接的代码上使用它,如:

HOST = get_current_host # this is the problem, how to get it?
@authorize_url = @client.authorize_url(@client.client_id,
                                      {
                                      :redirect_uri => "#{HOST}/step2", 
                                      :scope => 'public_repo,user,gist,admin:repo_hook,gist'
                                      })

所以,我的问题是如何在heroku 上获取当前正在运行的主机,所以我的代码可以用于测试和生产?

1 个答案:

答案 0 :(得分:0)

您可以为different environments

配置不同的值

下面给出一个简单的例子:

# File: test.rb
require 'sinatra'

# Set the values of various host names based on deployment environment
configure(:production) { set :host, "production-host" }
configure(:development) { set :host, "development-host" }
configure(:test) { set :host, "test-host" }

get '/' do
  "Hi #{settings.host}"
end

RACK_ENV环境变量设置为环境值 - productiondevelopmenttest

>set RACK_ENV=test

运行Sinatra App

>ruby test.rb
[2015-12-17 20:20:46] INFO  WEBrick 1.3.1
[2015-12-17 20:20:46] INFO  ruby 2.1.7 (2015-08-18) [x64-mingw32]
== Sinatra (v1.4.6) has taken the stage on 4567 for test with backup from WEBrick
[2015-12-17 20:20:46] INFO  WEBrick::HTTPServer#start: pid=11040 port=4567

访问网址:

>curl http://localhost:4567
Hi test-host

如果您使用Rack运行Sinatra应用程序,则可以关注config.ru

# config.ru
require 'sinatra'
require './test.rb'

configure(:production) { set :host, "production-host" }
configure(:development) { set :host, "development-host" }
configure(:test) { set :host, "test-host" }

run Sinatra::Application

在这种情况下,test.rb将简化如下:

# test.rb
require 'sinatra'

get '/' do
  "Hi #{settings.host}"
end

您可以在命令行上指定环境,如下所示:

> rackup -E test config.ru

这个答案的灵感来自Sinatra configuring environments on the fly