user3591056
user3591056

Reputation: 21

How to use mouse hover in Capybara with ruby?

I have tried the following in Capybara with Selenium but it did not work.

find('#element').trigger(:mouseover)
or
page.find("#element").click
or
page.execute_script("$('#element').trigger('mouseover')")
or
find(:css,#element').hover
or
**capybara webkit**
one also i tried nothing worked. Can you please suggest?

Upvotes: 2

Views: 2642

Answers (2)

user3114072
user3114072

Reputation:

When nothing works, you can simulate what's going on behind the scenes.

Given my HTML (body)

<body>

    <div id="myHiddenDiv">
        <a href="to/home/">A (not visible) link I'd like to click on</a>
    </div>

</body>

Given my CSS:

div#myHiddenDiv
{
    visibility: hidden;
}
div#myHiddenDiv:hover
{
    visibility: visible;
}

Without jQuery, without webkit (but with Selenium), I can do:

feature 'My div becomes visible' do

    scenario 'I can fake mouseover' do

        expect(page).not_to have_tag('div#myHiddenDiv', visible: true);

        # As if I mouseovered
        page.execute_script(<<-JS)
            let div = 'document.querySelector('div#myHiddenDiv');
            div.style.visibility = 'visible';
        JS

        expect(page).to have_tag('div#myHiddenDiv', visible: true);

        click_link("A (not visible) link I'd like to click on")

        # And go on!…

    end
end

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44725

Try:

page.execute_script("$('#element').trigger('mouseenter')")

For a clean solution, you need to have capybara-webkit gem installed. In your spec_helper add:

RSpec.configure do |config|
  # ... Your configuration
  Capybara.javascript_driver = :webkit
end

With this you should be able to trigger events with:

page.find('#element').trigger(:mouseover)

Upvotes: 1

Related Questions