Rails: Capybara::ElementNotFound



我正在尝试解决一个挑战,但我收到来自 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 和轨道 4.1.0。我是 ruby/rails 的初学者,我无法弄清楚我的代码出了什么问题。有人可以帮我解决这个问题吗?我提前表示赞赏。

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

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

或:

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

您也可以尝试使用小写Name

fill_in 'name', with: "Vostro 2017"

Capybara 将针对名称或 id 属性,因此第二个示例应该有效。

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'

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

f.label :name, 'Name'

我意识到我做错了什么,所以让我们开始吧:我将 def show 动作中的实例变量项更改为项(非复数),并将 atribute 从 assetNumber 更改为 asset_number,因此这样 Cabybara 测试就可以正确理解。

谢谢大家。

最新更新