How to fill hidden field with Capybara?

RspecCapybara

Rspec Problem Overview


I've already found that when I want to set value to text field, text area or password field, I can use id, name or label as something in fill_in something, :with => some_value. However such approach fails when I try to set value to <input type="hidden"> field (and I want to do it because those are normally filled client-side scripts which I test separately). How could I set such a hidden field with Capybara? Is it possible?

HTML:

<input id='offer_latitude' name='offer[latitude]' type='hidden'>
<input id='offer_longitude' name='offer[longitude]' type='hidden'>

spec:

describe "posting new offer" do
  it "should add new offer" do
    visit '/offer/new'
    fill_in 'offer[latitude]', :with => '11.11'
    fill_in 'offer[longitude]', :with => '12.12'
    click_on 'add'
  end
end

gives:

1) posting new offer should add new offer
   Failure/Error: fill_in 'offer[latitude]', :with => '11.11'
   Capybara::ElementNotFound:
     cannot fill in, no text field, text area or password field with id, name, or label 'offer[latitude]' found

Rspec Solutions


Solution 1 - Rspec

You need to locate the hidden field and set its value. There are a couple ways, this is probably the simplest

find(:xpath, "//input[@id='my_hidden_field_id']").set "my value"

If you're executing a client_side script in production, you could just tell capybara to run it with a javascript-compliant driver

page.execute_script("$('hidden_field_id').my_function()")

Solution 2 - Rspec

There are many ways to achieve the same result. The one I like the most is:

first('input#id.class', visible: false).set("your value")

Solution 3 - Rspec

If you're using poltergeist/phantomjs as a driver and jquery isn't working for ya, there's always good old fashioned js:

page.execute_script("document.getElementById('#some-id').value = 'some-value'");

Solution 4 - Rspec

This is what worked for me

find_field(id: 'your_hidden_field_id', type: :hidden).set('Field value here')

  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskaleeView Question on Stackoverflow
Solution 1 - RspecDVGView Answer on Stackoverflow
Solution 2 - RspecLuis D UrracaView Answer on Stackoverflow
Solution 3 - RspecpennerView Answer on Stackoverflow
Solution 4 - RspecKevyne SantosView Answer on Stackoverflow