我有一个rails应用程序,它的行为取决于它访问的域名(例如www.myapp.com将以不同方式调用user.myapp.com).在生产中使用这一切都很好但我的测试代码总是看到主机名"www.example.com".
是否有一种干净的方法让测试指定它假装访问的主机名?
我认为这里的所有答案都不完整......列举所有可能的案例:
集成规范(继承自:)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
视图规范文档.
@request.host = 'user.myapp.com'
在功能规格中,主持人!已被弃用.将这些添加到您的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
要记住的另一件事是确保使用正确的会话实例,以便您可以正确封装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
对于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