Rails:rspec中url helper的主机名错误

Url帮助程序(例如root_url)在app控制器和rspec示例中返回不同的主机名。 我已成功地在我的rails应用程序中为url helpers设置域,如下所示:

class ApplicationController < ActionController::Base def default_url_options {host: "foo.com", only_path: false} end end 

例如,root_url在应用程序中输出“http://foo.com/”,但在我的请求规范中输出“http://example.com”。 在rails 3.2中全局应用这些url选项的建议方法是什么,以便它们影响我的规范? url选项不需要是动态的。

在function规格中,主机! 已被弃用。 将这些添加到您的rspec_helper.rb:

 # Configure Capybara expected host Capybara.app_host = 'http://lvh.me:3000' # Configure actual routes host during test before(:each) do if respond_to?(:default_url_options) default_url_options[:host] = 'http://lvh.me:3000' end end 

只是为了添加Dan的答案,它在spec_helper.rb中看起来像这样

 RSpec.configure do |config| # other config options config.before(:each) do host! "localhost:3000" end end 

您可以在rspec中的测试中的前一个块中设置主机:

  before :each do host! 'hostgoeshere.com' end 

如果你想在全局设置它,你可以放一些你的spec_helper.rb文件。

我尝试了@request.host多种变体, host!post path, args, {'SERVER_NAME' => my_secret_domain}没有成功,无论是作为控制器测试还是function测试。 非常恶化,因为许多其他人报告说这些方法取得了成功。

我的解决方案是:

 request.headers["SERVER_NAME"] = my_secret_domain post path, args 

我正在运行ruby 2.1.5p273,rspec 3.1.7和Rails 4.2.0