当前位置:  开发笔记 > 开发工具 > 正文

如何更改默认的"www.example.com"域以便在rails中进行测试?

如何解决《如何更改默认的"www.example.com"域以便在rails中进行测试?》经验,为你挑选了5个好方法。

我有一个rails应用程序,它的行为取决于它访问的域名(例如www.myapp.com将以不同方式调用user.myapp.com).在生产中使用这一切都很好但我的测试代码总是看到主机名"www.example.com".

是否有一种干净的方法让测试指定它假装访问的主机名?



1> deivid..:

我认为这里的所有答案都不完整......列举所有可能的案例:

集成规范(继承自:)ActionDispatch::IntegrationTest:

host! "my.awesome.host"

请参阅文档,第5.1节" 可用于集成测试的助手".

控制器规格(继承自ActionController::TestCase)

@request.host = 'my.awesome.host'

请参阅文档,第4.4节" 可用的实例变量".

特征规格 (通过水豚)

Capybara.default_host = "http://my.awesome.host"
# Or to configure domain for route helpers:
default_url_options[:host] = "my.awesome.host"

来自@ AminAriana的回答

查看规范(继承自ActionView::TestCase)

@request.host = 'my.awesome.host'

......或通过RSpec:

controller.request.host = "my.awesome.host"

请参阅rspec-rails 视图规范文档.



2> jcrossley3..:
@request.host = 'user.myapp.com'


我如何在RSpec中使用它?我的意思是,我在哪里配置它?非常感谢!
@FRAGA:RSpec中的配置:请查看http://stackoverflow.com/a/7050306/2066546.`Capybara.app_host ="http://example.com"`对我有用.
在控制器规范中,我在尝试使用`host!`时出错.设置`@ request.host`就像回答建议的那样有效.

3> Amin Ariana..:

在功能规格中,主持人!已被弃用.将这些添加到您的rspec_helper.rb:

# Configure Capybara expected host
Capybara.app_host = "http://test.domain"

# Configure actual routes host during test
before(:each) do
  default_url_options[:host] = 
end


注意:似乎`Capybara.app_host`需要包含协议.例如``http://test.domain"`而不仅仅是`"test.domain"`.
如何包含端口?
在此上浪费的时间是荒谬的。谢谢。这是唯一有效的方法。为什么在世界上通过在Rails`config / environments / test.rb`中定义默认的url选项不能“正常工作”,这超出了我的范围。

4> mastaBlasta..:

要记住的另一件事是确保使用正确的会话实例,以便您可以正确封装url帮助程序.

集成测试为您提供默认会话.您可以直接从测试中调用所有会话方法

test "should integrate well" do
  https!
  get users_path
  assert_response :success
end

所有这些帮助程序都使用默认会话实例,如果不更改,则转到"www.example.com".如前所述,可以通过主机来更改主机!("my.new.host")

如果使用open_session方法创建多个会话,则必须始终使用该实例来调用帮助程序方法.这将正确封装请求.否则rails将调用可能使用不同主机的默认会话实例:

test "should integrate well" do
  sess = open_session
  sess.host! "my.awesome.host"
  sess.get users_url             #=> WRONG! will use default session object to build url.
  sess.get sess.users_url        #=> Correctly invoking url writer from my custom session with new host.
  sess.assert_response :success
end

如果您打算使用默认会话对象,那么您还必须更改该主机:

test "should integrate well" do
  sess = open_session
  sess.host! "my.awesome.host"
  host! sess.host              #=> Set default session host to my custom session host.
  sess.get users_url
end 



5> Nuno Silva..:

对于Rspec请求规格,请使用 before(:each) { host! 'example.com' }

在以下网址 查看更多信息:https : //relishapp.com/rspec/rspec-rails/v/3-6/docs/request-specs/request-spec https://github.com/rspec/rspec-rails/issues/1662 #issuecomment-241201056

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有