水豚使用 find() 检测 CSS ID 模型 ID



我目前正在内部网上工作,其中包括创建发票。

在编写测试时,我使用 Rspec 和 Capybara 进行测试,在运行请求测试时,我想创建发票并添加几个项目以确保正确计算增值税。

但是,我似乎遇到了一个问题,Capybara 找到了第一个 #item_price 并尝试匹配它而不是新创建的项目。

下面是我的请求测试中的一些代码。

...
...
# Laptop for 369.96 inc vat
click_link "Add Item"
fill_in "Quantity", :with => 1
fill_in "Price", :with => 369.96
fill_in "Description", :with => "laptop for 369"
click_button "Create Item"
page.should have_content("Item was successfully created")
find('#item_quantity').should have_content(1)
find('#item_price').should have_content(369.96)
find('#item_description').should have_content("laptop for 369")
find('#item_total').should have_content(369.96)
find('#invoice_subtotal').should have_content(308.30)
find('#invoice_vat').should have_content(61.66)
find('#invoice_total').should have_content(369.96)
# Laptop for 337.53 inc vat
click_link "Add Item"
fill_in "Quantity", :with => 1
fill_in "Price", :with => 337.53
fill_in "Description", :with => "laptop for 337"
click_button "Create Item"
page.should have_content("Item was successfully created")
find('#item_quantity').should have_content(1)
### the offending code below
find('#item_price').should have_content(337.53)
###
find('#item_description').should have_content("laptop for 337")
...
...

我希望能够添加#item_price_2其中 2 将是项目 ID。执行此操作并将find('#item_price').should have_content(337.53)更改为find('#item_price_#{invoice.id}').should have_content(337.53)时,我得到异常:

Nokogiri::CSS::SyntaxError:
unexpected '#' after '[#<Nokogiri::CSS::Node:0x007f991889f270 @type=:CONDITIONAL_SELECTOR, @value=[#<Nokogiri::CSS::Node:0x007f991889f3d8 @type=:ELEMENT_NAME, @value=["*"]>, #<Nokogiri::CSS::Node:0x007f991889f9c8 @type=:ID, @value=["#item_price_"]>]>]'

还将其更改为双引号"#item_price_{invoice.id}"给了我这个例外:

undefined local variable or method # 的发票

我猜这是因为我没有使用工厂女孩invoice所以还没有设置为一种方法。在这种情况下,我不使用 FactoryGirl,因为我想测试用户如何与发票和物料表单交互。

解决此问题的最佳方法是什么?有没有更好的方法来做我想做的事情?

提前非常感谢!

你关于尚未设置invoice的猜测是正确的。提交表单后,您可以设置它:

invoice = Invoice.last

然后你的规格应该通过。

最新更新