是否可以 fill_in 数字字段 wo/ 带有 Capybara 的标签?

Is it possible to fill_in a number field wo/ labels with Capybara?

我有一个数字字段,它带有一个 :product_quantity,后面有一个按钮 "Add to Cart"。我的测试在不调整 number_field 的情况下工作,但是当我取消注释这一行时:

product_from_shop.fill_in 'quantity', with: 5

东西爆炸了。 Capybara::ElementNotFound

在我看来是关于这一行的:

<%= f.number_field :product_quantity, value: booking.product_quantity, min: 1, max: 999, title: 'quantity' %>

我尝试了几种方法,还搜索了 class 或 id。非工作。没有标签,那会使我的视线混乱。

title 在其他情况下工作正常,没有表格。

另外:我用的是capybara webkit,因为它用的是JS。

假设您为此在 Rails 中使用 form_for,那么它应该会生成一个您可以使用的 ID。我不熟悉 product_from_shop.fill_in 形式,我通常使用 page,但尝试以下之一:

page.fill_in :product_from_shop_product_quantity, with: 5

page.fill_in "product_from_shop_product_quantity", with: 5

fill_in 使用 :fillable_field 选择器,它会找到任何可见的输入或文本区域元素,类型提交、图像、收音机、复选框或文件除外。它将找到那些元素的 id、名称或占位符属性,或者通过关联标签元素中的文本。由于您没有关联的标签,因此只能使用 id、name 或 placeholder 属性。假设 product_from_shop 是您用来限定此 fill_in 范围的页面上的包装元素,则

product_from_shop.fill_in '<something>_product_quantity', with: 5

应该通过 id 找到并 fill_in 元素 - 将取决于表单适用的模型类型(只需查看实际的 HTML 以查看分配的 id)。

如果产品数量字段是 product_from_shop 中唯一可填写的字段,您也可以这样做

product_from_shop.fill_in with: 5 # same as product_from_shop.fill_in nil, with: 5

如果其中 none 适合您,您可以转而使用

product_from_shop.find(<more complicated query>).set '5'

澄清您对 title 之前工作的评论 - title 属性仅在查找链接和按钮时匹配。