【问题标题】:Testing Devise - Capybara::ElementNotFound: Unable to find xpath "/html"测试设计 - Capybara::ElementNotFound: 找不到 xpath "/html"
【发布时间】:2026-02-11 04:40:01
【问题描述】:

我正在尝试使用 RSpec、Capybara 和 Factory Girl 测试我的网站的登录功能。我总是在终端中收到以下错误,但找不到任何解决方案。当我使用save_and_open_page 时,我得到一个空白页。我希望有人知道出了什么问题。谢谢!

这里是test output

Failure/Error: expect(page).to have_text("Login successful.")
     Capybara::ElementNotFound:
       Unable to find xpath "/html"
     # ./spec/features/navigation_spec.rb:49:in `block (2 levels) in <top (required)>'

这是我的sometest_spec.rb 文件和相应的行:

require 'spec_helper'
include Warden::Test::Helpers

describe "User login" do
  it "log in normal user" do

    Warden.test_mode!

    user = create(:normal_user)
    user.confirmed_at = Time.now
    user.save
    login_as(user, scope: :user)

    expect(page).to have_text("Login successful.")

    logout(:user)
    Warden.test_reset!
  end
end

这是我的factory_girl.rb 文件

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

还有factories.rb 文件

FactoryGirl.define do
  factory :normal_user, class: User do
    firstname "John"
    lastname "Doe"
    email "test@user.com"
    password "thepassword"
    admin false
  end
end

【问题讨论】:

  • 尝试使用 have_content 而不是 have_text ....不确定
  • 不,那不是没有修复它。我也在其他地方成功地使用了 have_text。似乎 login_as 方法没有任何重定向“影响”。

标签: ruby-on-rails rspec capybara factory-bot


【解决方案1】:

原来我必须在login_as 之后手动visit a_path 才能看到额外的登录页面内容。

【讨论】: