Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara testing value of hidden field

Tags:

capybara

I have a form with a hidden field that contains the current date.

I'm trying to figure out how to write a capybara finder to:

  1. Check that the field is there
  2. Check the value of the field

Is this possible with Capybara?

like image 327
Misha M Avatar asked Jan 02 '13 05:01

Misha M


People also ask

What is the concept hidden field?

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.


3 Answers

just do this:

find("#id_of_hidden_input", :visible => false).value
like image 78
Dominik Goltermann Avatar answered Oct 19 '22 06:10

Dominik Goltermann


You could also instruct Capybara to not ignore hidden elements globally in your spec_helper.rb or equivalent. The default behaviour can be overridden:

# default behavior for hidden elements
# Capybara.ignore_hidden_elements = false

# find all elements (hidden or visible)
page.all(".articles .article[id='foo']")

# find visible elements only (overwrite the standard behavior just for this query)
page.all(".articles .article[id='foo']", :visible => true)


# changing the default behavior (e.g. in your features/support/env.rb file)
Capybara.ignore_hidden_elements = true

# now the query just finds visible nodes by default
page.all(".articles .article[id='foo']")

# but you can change the default behaviour by passing the :visible option again
page.all(".articles .article[id='foo']", :visible => false)

Examples taken from this article.

like image 39
Darme Avatar answered Oct 19 '22 06:10

Darme


the matcher has_field? works with hidden fields as well. no need to do weird gymnastics with find or all in this context.

page.has_field? "label of the field", type: :hidden, with: "field value"
page.has_field? "id_of_the_field", type: :hidden, with: "field value"

the key here is setting the :type option to :hidden explicitly.

why use a label with a hidden field? this comes in handy if you're using a js library, like flatpickr, that cloaks your original text field to hide it. not coupling your behavior tests to specific markup is always a good thing.

like image 9
glasz Avatar answered Oct 19 '22 04:10

glasz