Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test for an empty input field?

I'm trying to test to see if an input field matches one of my factories where the field is empty.

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

When checking for what is in the input field I've been using this:

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

Except this does not work if the first name is blank. I'll get this error and the test fails.

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

This makes sense because the code generated will not have the value attribute. Is there a better way to verify the value of an input field?

As of now to test for this I can check if the address field is blank then check if there is an input field without a value attribute. But this is messy and verbose.

Example of a universal check that works but is lengthy:

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

Related Information I'm using:
Hpricot 0.8.1
Nokogiri 1.1.1
Rails 2.2.2
Thoughtbot-Shoulda 2.0.5
Webrat 0.4.1

like image 224
Vizjerai Avatar asked May 28 '09 19:05

Vizjerai


1 Answers

Maybe you can use:

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

I don't think I can get it any shorter. If it is a recurring pattern in your test case, you could extract it to a custom assertion:

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
like image 54
molf Avatar answered Nov 05 '22 15:11

molf