DuckPuppy
DuckPuppy

Reputation: 1366

Testing a link's target attribute with Capybara/RSpec

I'm a bit new to Rails/RSpec/Capybara, so this is probably a newbie question, but Google didn't help as much as I would have hoped. I was hoping that I could use

it { should have_link('link text', href: 'url', target: '_blank') }

to write a test for a link that should open in a new window, but that doesn't seem to work. I've also tried wrapping the options hash in curly-braces:

it { should have_link('link text', {href: 'url', target: '_blank'}) }

The test will always succeed regardless of the presence or value of the target attribute in the actual page and link being tested. Changing the href attribute does cause a test failure as expected. I thought the options hash for have_link was a list of attributes to test for. Apparently I'm wrong, but what's the best way to test a single link for it's target attribute? Hopefully it's not to use an XPath search...

Upvotes: 21

Views: 12485

Answers (4)

Eliot Sykes
Eliot Sykes

Reputation: 10063

Define a custom matcher that finds the link and checks its target attribute is '_blank':

RSpec::Matchers.define :have_link_open_in_new_window do |locator, options={}|
  match do |page|
    link = page.find_link(locator, options)
    link && link[:target] == '_blank'
  end
end

Use have_link_open_in_new_window(locator, options) as you'd use have_link(locator, options):

expect(page).to have_link_open_in_new_window('Link text or id', href: '...')

Upvotes: 1

dgilperez
dgilperez

Reputation: 10796

Using new rspec 3 syntax:

is_expected.to have_link('link_text', href: 'url')
expect(find_link('link_text')[:target]).to eq('_blank')

Upvotes: 13

Adam Waite
Adam Waite

Reputation: 18855

You could do:

it { should have_css "a[href~='/somewhere'][target~='_blank']" }

Upvotes: 5

Salil
Salil

Reputation: 9722

I am not sure why your code does not work. Have you tried this:

find_link('link_text')[:href].should == 'url'
find_link('link_text')[:target].should == '_blank'

Upvotes: 27

Related Questions