You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RSpec系统测试中为单个用例修改Capybara的request.host

修改RSpec系统测试中特定用例的Capybara request.host值

正确实现方式

针对你的需求,有两种可靠的方法可以在单个测试用例中修改请求的host:

方法1:临时修改Capybara.app_host

在测试用例内临时替换Capybara.app_host,测试完成后恢复原值,避免影响其他用例:

scenario "asdf user see asdf page" do
  create_asdf

  # 保存原host并设置新值
  original_app_host = Capybara.app_host
  Capybara.app_host = "http://www.example.2.com"

  visit root_path
  
  expect(page).to have_css("#asdf")

  # 恢复原host配置
  Capybara.app_host = original_app_host
end

方法2:在visit时直接指定host参数

如果不想修改全局配置,可以在调用visit时直接传入host参数:

scenario "asdf user see asdf page" do
  create_asdf

  visit root_path(host: "www.example.2.com")
  
  expect(page).to have_css("#asdf")
end

你代码中的问题

你尝试的!host 'example.2.com'是无效语法,既不符合Ruby语法规范,也不是Capybara提供的API调用方式,自然无法生效。

使用的gem版本

gem 'rspec-rails', '~> 3.5.0'
gem 'capybara', '~> 3.6.0'

内容的提问来源于stack exchange,提问作者daveasdf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:56:11