【问题标题】:Capybara::ElementNotFound: Unable to find visible fieldCapybara::ElementNotFound:找不到可见字段
【发布时间】:2018-02-22 23:29:12
【问题描述】:

我在终端中的 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

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

感谢专业人士的帮助。

【问题讨论】:

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


    【解决方案1】:

    您无法填写不可见的字段,因此将visible: false 传递给fill_in 是没有意义的。

    fill_in 没有找到您的字段的原因是它通过 id、名称或关联的标签文本来查找字段。您没有显示页面的实际 HTML,但“用户名”和“密码”实际上不在标签元素中,这意味着您无法通过关联的标签文本找到,因此无法正常工作。您可以将文本放入&lt;label&gt; 元素并与各个字段关联(for 属性或包装),或者您可以选择字段以通过 id 或名称填充。如果没有实际的 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'
    

    匹配字段名称属性。

    【讨论】:

    • 嘿,谢谢伙计,它有效!感谢您保存我的代码。非常感谢=)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多