Capybara: Trigger Blur Event

kinopyo avatar

kinopyo

I have a feature spec to test the Javascript behavior of the blur event, sadly Capybara's native DSL doesn't seem to support it yet.

After quick research, I found two options.

Simulate tab away from the element

field = find(target)
field.native.send_keys :tab

Click the page body

find("body").click

My Pick

Both worked for me, pick one you like. I prefer the first one, so what I end up is something like this:

module CapybaraActions
  def blur_from(locator)
    field = find_field(locator)
    field.native.send_keys :tab
  end
end

RSpec.configure do |config|
  config.include CapybaraActions, type: :feature
end

And to use it:

scenario "Save contents automatically", :js do
  fill_in "post_body", with: "Long time ago..."
  blur_from "post_body"

  expect(page).to have_content("Saved")
end

Tested with Capybara 3 with Headless Chrome.


Thanks to these posts:

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.