如何使用capybara检查预填充的表单字段是否为空?

时间:2017-06-15 02:57:55

标签: ruby automated-tests cucumber capybara

我想检查这个字段,它的值是否为空?

<input name='phone_number' type='text'>

我试过

expect(@browser.phone_number.value.to_s).exist expect(@browser.phone_number.value).exist expect(@browser.phone_number.value).be_truthy expect(@browser.phone_number).exist expect(@browser.phone_number).to be_truthy expect(@browser.phone_number).to exist

但是当字段的值为空时,它不是错误

我希望当值不为null时传递场景 值为空时出错

1 个答案:

答案 0 :(得分:0)

You don't specify what @browser and phone_number are but I'm going to assume they're from a page object model using something like SitePrism.

When not using a page object model this would be exactly what the :with option of the :field selector is for. It can take a regex or a string to match the current field value against. Therefore we can check for a field with name of 'phone_number' and a value that has at least one character with

expect(page).to have_field('phone_number', with: /.+/) 

How you use that option with a page object model depends on exactly how you've implemented the page object model, but it usually boils down to the implementation finally calling find with the :field selector type and the options above. If using SitePrism that would mean

class MyPage < SitePrism::Page
  ...
  element :phone_number, :field, 'phone_number' # define phone_number to use the 'field' selector type
end

@browser = MyPage.new
expect(@browser).to have_phone_number(with: /.+/)