Rspec/Capybara断言期望example.com却得到localhost,求解决方法
解决测试中URL主机/端口不匹配的问题
问题描述
测试用例输出:
期望: "http://www.example.com:3000/admin/biblebooks/1"
实际得到: "http://127.0.0.1:61574/admin/biblebooks/1"
已尝试设置apphost,仍未解决,测试代码如下:
feature "Admins can create new bible books" do before do login_as(create(:user, :admin)) visit admin_biblebooks_path click_link t(:new_biblebook) end scenario "for single bible books" do bookname = "Handelingen" fill_in t("simple_form.labels.biblebook.name"), with: bookname fill_in t("simple_form.labels.biblebook.booksequence"), with: 0 fill_in t("simple_form.labels.biblebook.testament"), with: "nieuw" submit_form should_see t(:item_created, item: Biblebook.model_name.human) book = Biblebook.find_by(name: "Handelingen") expect(page.current_url).to eq admin_biblebook_url(book) end end
解决思路
完整配置Capybara的主机和端口参数
仅设置app_host不够,需要同步配置服务器绑定的地址和端口,在测试配置文件(如rails_helper.rb)中添加:Capybara.app_host = "http://www.example.com:3000" Capybara.server_host = "www.example.com" Capybara.server_port = 3000同时要确保本地
hosts文件里有127.0.0.1 www.example.com的映射,否则测试服务器无法被访问。改用路径校验替代完整URL校验
如果不需要严格验证主机和端口,可以只断言URL的路径部分,避免环境差异干扰测试:# 校验路径包含目标路由 expect(page.current_url).to include(admin_biblebook_path(book)) # 或更精准的路径匹配 expect(page).to have_current_path(admin_biblebook_path(book), url: true)配置Rails测试环境的默认URL参数
在config/environments/test.rb中设置Rails URL生成的默认主机和端口,让admin_biblebook_url生成的URL与期望一致:Rails.application.configure do # 其他配置项... config.action_controller.default_url_options = { host: 'www.example.com', port: 3000 } end检查驱动特定配置
如果使用Selenium等外部驱动,需要单独配置驱动的访问地址,比如:Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, browser: :chrome, url: "http://www.example.com:3000") end
内容的提问来源于stack exchange,提问作者andreheijstek
相关产品推荐
相关产品推荐

