Capybara::ElementNotFound: 无法找到可见字段

Capybara::ElementNotFound: Unable to find visible field

我在终端中的 Capybara 测试收到以下错误:

Failures:

  1) Users User create new user
     Failure/Error: fill_in 'Username', with: 'Ali', visible: false

     Capybara::ElementNotFound:
       Unable to find field "Username" that is not disabled within #<Capybara::Node::Element tag="form" path="/html/body/form">
     # ./spec/features/users_spec.rb:31:in `block (4 levels) in <top (required)>'
     # ./spec/features/users_spec.rb:30:in `block (3 levels) in <top (required)>

我在水豚中的测试代码:

require 'rails_helper'
RSpec.feature "Users", type: :feature do
  describe "User", :type => :feature do
    it "create new user" do
      visit '/signup'
      within('form') do
        fill_in 'Username', with: 'Ali', visible: false
        fill_in 'Password', with: 'ali', visible: false
      end
      click_button 'Submit'
      expect(page).to have_content 'User successfully created.'
    end
  end
end

我的查看文件

<h1>Create New User</h1>
<%= form_for :user, url: '/users' do |f| %>
  Username: <%= f.text_field :username %>
  Password: <%= f.password_field :password %>
  Uplaod your photo: <%= f.file_field :image %>
<%= f.submit "Submit" %>
<% end %>

我的控制器:

  def create
    user = User.new(user_params)
    if user.save
      redirect_to '/users/index', notice: 'User successfully created.'
    else
      redirect_to '/signup'
    end
  end

我做了一些研究,这是由于水豚 2x 的问题,大多数人通过添加 visible: false 来解决,但这个解决方案对我不起作用。

感谢专业人士的帮助。

您不能填写 non-visible 的字段,因此将 visible: false 传递给 fill_in 没有任何意义。

fill_in 找不到您的字段的原因是它按 ID、名称或关联的标签文本查找字段。您没有显示页面的实际 HTML 但 'Username' 和 'Password' 实际上不在标签元素中的事实意味着您无法通过关联的标签文本找到所以那是行不通的。您可以将文本放入 <label> 元素并与相应的字段关联(for 属性或包装),或者您可以 select 通过 ID 或名称将字段 fill_in 关联。没有实际的 HTML 就不可能肯定地说,但是像

fill_in 'user_username', with: 'Ali'
fill_in 'user_password', with: 'ali'

可能会工作,匹配字段 ID,

fill_in 'user[username]', with: 'Ali'
fill_in 'user[password]', with: 'ali'

匹配字段名称属性。

我用这种方法解决了同样的问题: 在我的一些 js 代码中是 `` 而不是 ''。浏览器可以理解该语法(它``需要插值),但 Capybara 不能。

当我将 `` 更改为 '' 时,问题就消失了。