views:

48

answers:

3

I would like this custom step:

Then I should see the link 'foo'

and his opposite:

But I should not see the link 'foo'

In the page I can have something like:

lorem foo bar

or alternatively

lorem <a href=''>foo</a> bar

I need to test when 'foo' is a link and when isn't. Thank you.

A: 

There are already pre-defined Webrat steps which do this (or are at least very similar). From web_steps.rb

Then /^(?:|I )should see \/([^\/]*)\/ within "([^\"]*)"$/ do |regexp, selector|
  within(selector) do |content|
    regexp = Regexp.new(regexp)
    if defined?(Spec::Rails::Matchers)
      content.should contain(regexp)
    else
      assert_match(regexp, content)
    end
  end
end

and

Then /^(?:|I )should not see "([^\"]*)" within "([^\"]*)"$/ do |text, selector|
  within(selector) do |content|
    if defined?(Spec::Rails::Matchers)
      content.should_not contain(text)
    else
      hc = Webrat::Matchers::HasContent.new(text)
      assert !hc.matches?(content), hc.negative_failure_message
    end
  end
end
bjg
Can you please write here an example for a word within a link, I tried with no success:And I should see "foo" within "a"And I should see "foo" within "[a]"And I should see "[foo]" within "[a]"but it doesn't work.
Leonardo Dario Perna
A: 

Try something like this (I haven't tried running it, so minor tweaks might be needed):

Then /^I should see the link "([^\"]*)"$/ do |linked_text|
  # AFAIK this raises an exception if the link is not found
  find_link(linked_text)
end

Then /^I should not see the link "([^\"]*)"$/ do |linked_text|
  begin
    find_link(linked_text)
    raise "Oh no, #{linked_text} is a link!"
  rescue
    # cool, the text is not a link
  end
end
Paolo Dona
undefined method `find_link' for #<Cucumber::Rails::World:0x8170bb84> (NoMethodError)
Leonardo Dario Perna
A: 

You might have more luck using xpaths for this, you could use something like "//a/text()='foo'". You just need to enable xpaths for webrat, I wrote a blog post about doing something similar with xpaths in tables here http://www.opsb.co.uk/?p=165, it includes the code required to enable xpaths for webrat.

opsb