简体   繁体   English

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

[英]Rails: Wrong hostname for url helpers in rspec

Url helpers (eg root_url) returns a different hostname in the app controllers vs rspec examples. Url帮助程序(例如root_url)在app控制器和rspec示例中返回不同的主机名。 I have successfully been able to set the domain for url helpers in my rails app like this: 我已成功地在我的rails应用程序中为url helpers设置域,如下所示:

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

For example, root_url outputs "http://foo.com/" within the application but "http://example.com" in my request specs. 例如,root_url在应用程序中输出“http://foo.com/”,但在我的请求规范中输出“http://example.com”。 What is the recommended way to apply those url options globally in rails 3.2 so that they affect my specs? 在rails 3.2中全局应用这些url选项的建议方法是什么,以便它们影响我的规范? The url options do not need to be dynamic. 网址选项不需要是动态的。

In Feature specs, host! 在功能规格中,主机! has been deprecated. 已被弃用。 Add these to your rspec_helper.rb: 将这些添加到您的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

Just to add to Dan's answer it would look something like this in spec_helper.rb 只是为了添加Dan的答案,它会在spec_helper.rb中看起来像这样

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

You can set the host in a before block in your test in rspec: 您可以在rspec中的测试中的前一个块中设置主机:

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

If you want to set it globally you could put something your spec_helper.rb file. 如果你想在全局设置它,你可以放一些你的spec_helper.rb文件。

I tried many variations of @request.host , host! 我试过很多@request.host变种, host! , and post path, args, {'SERVER_NAME' => my_secret_domain} without success, both as controller tests and feature tests. post path, args, {'SERVER_NAME' => my_secret_domain}没有成功,无论是作为控制器测试还是功能测试。 Very aggravating, as so many others reported success with those approaches. 非常恶化,因为许多其他人报告说这些方法取得了成功。

The solution for me was: 我的解决方案是:

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

I'm running ruby 2.1.5p273, rspec 3.1.7 and Rails 4.2.0 我正在运行ruby 2.1.5p273,rspec 3.1.7和Rails 4.2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM