AlbertMunichMar
AlbertMunichMar

Reputation: 1866

Rails project, testing with capybara a hidden field: Selenium::WebDriver::Error::ElementNotVisibleError: element not visible

(the other stackoverflow answers do not answer my question)

I have a form with a hidden_field_tag:

<form action="/score" method="post">
  <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
  <%= hidden_field_tag :letters, @letters, id: "idgrid" %>
  <input type="text" name="word" placeholder="type world">
  <input type="submit" value="send">
</form>

I want to run following test with capybara (minitest)

require "application_system_test_case"

class GamesTest < ApplicationSystemTestCase
  test "word in the grid but not english" do
    visit new_url
    fill_in "word", with: "car"
    find('#idgrid', visible: false).set("N e w t e x t")
    click_on "send"

    assert_text "Sorry, can't build from grid"
  end
end

I get following error

Error:
GamesTest#test_word_in_the_grid_but_not_english:
Selenium::WebDriver::Error::ElementNotVisibleError: element not visible
  (Session info: headless chrome=68.0.3440.106)
  (Driver info: chromedriver=2.41.578706 (5f725d1b4f0a4acbf5259df887244095596231db),platform=Mac OS X 10.13.6 x86_64)
    test/system/games_test.rb:22:in `block in <class:GamesTest>'

I have read the other stackoverflow questions related to the topic, and not find the right answer. Also github issues. I understand that the element is not visible, but I have read that capybara can set the value, if I use the visible: false.

Could someone please help me?

Thanks

Upvotes: 1

Views: 626

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49880

With Capybara you can find and inspect non-visible elements but you can't directly set their values because a normal user can't and therefore it doesn't really make a lot of sense to be directly changing them in feature/system tests. If you really need to change a hidden fields value you will need to do so via JS using something like

find('#idgrid', visible: false).execute_script("this.value = "N e w t e x t")

Since this doesn't replicate behavior a user would normally do, it's generally considered bad practice in feature/system tests and you really should think about whether there's better way of setting up those fields values that actually replicates a user (or if it makes more sense as a different type of test).

Upvotes: 1

Related Questions