Search code examples
ruby-on-railscapybarasimple-form

Testing a simple_form with capybara


I have a simple_form:

= simple_form_for @client_email, url: { action: "update" }, html: {class: "search_form",  method: :put } do |f|
  = f.error_notification

  .input-row
    = f.input :old_domain, :label => "Old domain name", required: true , input_html: {name: 'search_term'}
    = f.input :new_domain, :label => "New domain name", required: true

[with extra stuff at the bottom for submitting]

I'm trying to test it with capybara/cucumber.

I can ender stuff into :old_domain with:

@session.fill_in('search_term', with: search_term)

However, I can't figure out what to use for "new_domain"... I've tried adding an id: to the f.input line, but that didn't help...

the :new_domain line in the HTML is:

<div class="input string required client_email_new_domain">
   <label class="string required control-label" for="client_email_new_domain">
      <abbr title="required">*</abbr> New domain name</label>

   <input class="string required" id="client_email_new_domain" 
      name="client_email[new_domain]" type="text" /></div>

ETA: I BELIEVE that it should be looking for the name field, so "client_email[new_domain]", but I get the capybara error:

  Unable to find field "client_email[new_domain]" (Capybara::ElementNotFound)
  ./features/pages/change_client_domains_page.rb:22:in `to_domain'
  ./features/step_definitions/change_client_domains_steps.rb:18:in `/^I set to_domain to "(.*?)"$/'
  features/admin/change_client_domains.feature:42:in `And I set to_domain to "neworg.com"'

Solution

  • fill_in takes the inputs id, name, placeholder, or associated label text so given the HTML provided any of the following should fill in the new domain input

    fill_in 'client_email_new_domain', with: 'whatever'
    fill_in 'client_email[new_domain]', with: 'whatever'
    fill_in 'New domain name', with: 'whatever'
    

    If any of those don't work then you're not actually on a page with the visible HTML you think is there. In that case use @session.save_and_open_screenshot to see what the page actually looks like, and look at @session.html to see what the HTML of the page actually is when you're trying to fill it in (assumes @session is actually the Capybara session you're testing in - use page otherwise for the current session).

    One thing to look out for is if you're attaching any JS widget behavior to the inputs which hides the original input. If you are then you need to interact with the visible elements the widget adds to the page rather than the hidden original input element.

    A final possibility is that @session isn't actually the session you visited the page in. Not really sure why you're passing around the current session in an instance variable unless you're testing with multiple sessions?