【问题标题】:How do you test for an empty input field?你如何测试一个空的输入字段?
【发布时间】:2009-05-29 16:45:44
【问题描述】:

我正在尝试测试输入字段是否与我的字段为空的工厂之一匹配。

address => {:first_name => '', :last_name => ''}

在检查输入字段中的内容时,我一直在使用这个:

assert_select '#first_name[value=?]', address.first_name

除非名字为空,否则这不起作用。我会得到这个错误并且测试失败。

Expected at least 1 element matching "#first_name[value='']", found 0.
<false> is not true.

这是有道理的,因为生成的代码将没有 value 属性。有没有更好的方法来验证输入字段的值?

到目前为止,要对此进行测试,我可以检查地址字段是否为空白,然后检查是否存在没有值属性的输入字段。但这是混乱和冗长的。

有效但冗长的通用检查示例:

if address.first_name.blank?
  assert_select '#first_name[value]', 0
  assert_select '#first_name[type=text]', 1
else
  assert_select '#first_name[value=?]', address.first_name
end

我正在使用的相关信息:
Hpricot 0.8.1
Nokogiri 1.1.1
Rails 2.2.2
Thoughtbot-Shoulda 2.0.5
Webrat 0.4.1

【问题讨论】:

标签: ruby-on-rails testing


【解决方案1】:

也许你可以使用:

assert_select "#first_name" do
  assert_select "[value=?]", address.first_name unless address.first_name.blank?
end

我想我不能再短了。如果它是您的测试用例中重复出现的模式,您可以将其提取到自定义断言中:

def assert_has_value_unless_blank(selector, value)
  assert_select selector do
    assert_select "[value=?]", value unless value.blank?
  end
end

assert_has_value_unless_blank "#first_name", address.first_name

【讨论】:

  • 这似乎并没有测试输入元素是否为空,如果传入的值为空,它只是跳过对 value 属性的测试。
猜你喜欢
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2020-07-28
相关资源
最近更新 更多