Rails - Capybara, populate hidden field from trix-editor

2.1k views Asked by At

I use Trix Editor to have WISIWIG in my form. I want to test with RSpec and Capybara but trix-editor put the field hidden.

<div class="form-group">
  <trix-editor class="formatted_content form-control" placeholder="Description" input="annonce_ad_body_trix_input_annonce_ad"></trix-editor><input type="hidden" name="annonce_ad[body]" id="annonce_ad_body_trix_input_annonce_ad" />
</div>

I need to know how i can fill this hidden field with Capybara to make my test pass. I have try these attemp:

fill_in "annonce_ad[body]", with: "my value"
find(:css, 'trix-editor').set("New text")
find("trix-editor", visible: false).set("my value")
find(:xpath, "//input[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set "my value"
find(:xpath, "//*[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set("value")
first('input#annonce_ad_body_trix_input_annonce_ad.class', visible: false).set("your value")

None of these have work for me. Someone have any idea how i can fill my body(with trix) in this case?

2

There are 2 answers

2
Gabriel Sigouin On

I make a mistake, this work for me.

find(:xpath, "//*[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set("some value here")
1
Thomas Walpole On

When using Capybara the rule when dealing with non-standard controls is to mimic what the user would do. In this case that would be click on the visible field (trix-editor element) and then type the contents wanted. You should never be trying to fill in non-visible elements and in fact the visible option should rarely (if ever) be used when testing an app (makes some sense if using Capybara for scraping). So in your case that should be

find('trix-editor').click.set('New text')

It would probably work without the click, but it doesn't hurt to more fully replicate the user. Since you've stated that something very similar to that doesn't work for you (but not provided the actual error) I have to assume you're not actually using a JS capable driver. Since trix is a JS driven editor you need to use a JS capable driver when testing it - https://github.com/teamcapybara/capybara#drivers .

The following basic ruby snippet shows Capybara filling in the demo trix editor at trix-editor.org

require 'capybara/dsl'
require 'selenium-webdriver'

sess = Capybara::Session.new(:selenium_chrome, nil)
sess.visit('https://trix-editor.org/')
editor = sess.find('trix-editor')
editor.click.set('My test text')
editor.assert_text('My test text')