[rspec-users] have_tag with a block

s.ross cwdinfo at gmail.com
Wed Feb 4 14:27:37 EST 2009


On Feb 3, 2009, at 9:44 PM, MarkMT wrote:

> Thanks David. Those specs are very instructive. I have no idea what I
> was doing wrong before, but the behavior I'm seeing now is indeed
> consistent with the specs and matches what I had understood from the
> code I'd looked at (I suspect it'll stop working as soon as I send
> this :-) ).
> Actually my situation is slightly more complex than what the specs
> cover. I have something like this -
> <div id="registration_link">
>  New user? Register <a href="/User/register">here</a>
> </div>
> and I'm testing it with a cucumber step that looks like this -
> Then /^the response should contain a link to new user registration$/
> do
>  @response.should have_tag('div', :id =>'registration_link', :content
> => 'New User? Register ') { |match|
>    match.should have_tag('a', :href => '/User/register', :content =>
> 'here')
>  }
> end
> One of the things I was unsure about was whether I could mix both the
> text content and the second tag inside the outer element. Turns out
> that this works just fine with the test above. Also, have_tag
> ('div#registration_link'...) works just as well as have_tag('div', :id
> => 'registration_link'...)

I'm writing a similar kind of scenario and want to make sure I am  
scoping my "assertion" (if you will) to the stuff inside the tag. The  
idea is that all people to whom this page is addressed are on the  
address line (but not necessarily the only thing on the address line.  
So the first guess was:

<div id="address-line">
   joe, bob

recipients.split(/,\s*/).each do |recipient|
   response.should have_tag('div[address-line]', recipient)

This doesn't work. Change the expectation to:

   response.should have_tag('div[address-line]', Regexp.new(recipient))

and, predictably, it works. But is that scoped to include only text  
that matches the regexp within the div[address-line]?

The code I really wanted to write (phrase stolen from the RSpec Book)  

recipients.split(/,\s*/).each do |recipient|
   response.should have_tag('div[address-line]') do |r|
     r.should include(recipient)

But that gives me a failed expectation showing a gruesomely  
complicated representation of the page DOM and comparing it to 'joe'.

Question: Is there an accepted way to scope text substrings to within  


More information about the rspec-users mailing list