【问题标题】:Rails: Capybara::ElementNotFound导轨:Capybara::ElementNotFound
【发布时间】:2017-10-26 03:29:18
【问题描述】:

我正在尝试解决一个挑战,但我收到了来自 Cabybara 的错误消息:

`Failure/Error: fill_in 'Name', with: 'Vostro 2017'   
     Capybara::ElementNotFound: Unable to find visible field "Name" that is not disabled`

我的new.html.erb 是:

<%= form_for @item, url: {action: "create"} do |f|%>
  <%= f.label 'Name' %>
  <%= f.text_field :name %>
  <%= f.label 'Description' %>
  <%= f.text_field :description %>
  <%= f.label 'Features' %>
  <%= f.text_field :features %>
  <%= f.label 'Asset number' %>
  <%= f.text_field :assetNumber %>
  <%= f.submit%>
<% end %>

而我的item_controller.rb 是:

class ItemController < ApplicationController
  def show
    @items = Item.find(params[:id])
  end
  def new
    @item = Item.new
  end

  def create
    @item = Item.new(item_params)

    @item.save
    redirect_to @item
  end

  private
  def item_params
    params.require(:item).permit(:name, :description, :features, :assetNumber)
  end
end

用于进行测试的 rspec 文件是:

require 'rails_helper'

feature 'User creates a new inventory item' do
  scenario 'successfully' do
    visit new_item_path
    fill_in 'Name', with: 'Vostro 2017'
    fill_in 'Description', with: 'Dell Notebook'
    fill_in 'Features', with: '16gb, 1Tb, 15.6"'
    fill_in 'Asset number', with: '392 DLL'
    click_button 'Create Item'

    expect(page).to have_content 'Vostro 2017'
    expect(page).to have_content 'Dell Notebook'
    expect(page).to have_content '16gb, 1Tb, 15.6"'
    expect(page).to have_content '392 DLL'
  end
end

我正在使用 ruby​​-2.3.5 和 rails 4.1.0。 我是 ruby​​/rails 的初学者,我不知道我的代码有什么问题。 有人可以帮我解决这个问题吗? 我提前感谢。

【问题讨论】:

  • 你能否用模态更新问题。
  • @Ziyan Junaideen 什么是模态?

标签: ruby-on-rails ruby rspec capybara


【解决方案1】:

假设您的输入的 id 为 name,您可以这样做:

find("input[id$='name']").set "Vostro 2017"

或:

find("#name").set "Vostro 2017"

你也可以试试小写Name

fill_in 'name', with: "Vostro 2017"

Capybara 将定位 name 或 id 属性,因此第二个示例应该可以工作。

【讨论】:

  • 挑战的所有者不喜欢更改测试文件。
【解决方案2】:

Rails 使用表单对象生成表单输入名称。

fill_in 'item[name]', with: "Vostro 2017"
fill_in 'item[description]', with: 'Dell Notebook'
fill_in 'item[features]', with: '16gb, 1Tb, 15.6"'
fill_in 'item[assetNumber]', with: '392 DLL'

【讨论】:

    【解决方案3】:

    如果您查看页面的实际 HTML 而不是 erb 模板(最好包含 HTML,除非您的问题专门针对 erb),您会注意到您的标签实际上并未与输入元素相关联(没有与输入 id 匹配的 for 属性)。显然,Capybara 通过标签文本(在您的情况下为“名称”)查找元素,标签必须与元素正确关联。要解决此问题,您需要正确使用 f.label - http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-label -。如果你想指定元素的文本(与使用从 i18n 翻译中提取的文本相比),那将是

    f.label :name, 'Name'
    

    【讨论】:

    • 很棒的提示。非常感谢。
    【解决方案4】:

    我意识到我做错了什么,所以让我们开始吧: 我将 def show action 中的实例变量 items 更改为 item(不是复数形式),并将属性从assetNumber 更改为asset_number,因此 Cabybara 测试可以正确理解。

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多