[rspec-users] Problem with Custom matcher and Blocks

Brandon Olivares programmer2188 at gmail.com
Fri Apr 3 22:21:57 EDT 2009


I've still been working on this, and can't figure it out.

I did see this old thread that covers a similar problem down the page a bit:

The OP eventually links to a project where it explains how to do what he was
trying to do, which is here:

So I looked through, and it seems promising, but it's still not working.

I mean that the difference is that he is doing something like:

response.should have_form('/users') do
with_text_field 'First name', 'user_first_name'

Etc. But I want to pass a variable to the block with the scope, so I want to
do something like:

response.should have_form('/users') do |form|
form.should have_text_field 'First name'

I find that more readable.

So does anyone know how I can do this?

Also, in this person's code, he passes a scope to the matcher, like:

Def have_form(action, &block)
HaveForm.new action, self, &block

And then he uses it in matches? Like:

response.should @scope.have_tag('form[action=?]', @action) do |form|
@block.call if @block

So I'm stumped. Any help would be much appreciated, as I've been working on
this for at least three days now.


> -----Original Message-----
> From: Brandon Olivares [mailto:programmer2188 at gmail.com]
> Sent: Thursday, April 02, 2009 7:04 PM
> To: 'rspec-users'
> Subject: RE: [rspec-users] Problem with Custom matcher and Blocks
> > -----Original Message-----
> > From: rspec-users-bounces at rubyforge.org [mailto:rspec-users-
> > bounces at rubyforge.org] On Behalf Of Matt Wynne
> > Sent: Thursday, April 02, 2009 6:04 PM
> > To: rspec-users
> > Subject: Re: [rspec-users] Problem with Custom matcher and Blocks
> >
> >
> > I don't think you want to be using #should here. If that fails it
> will
> > raise an exception but the expected behaviour of a matcher is to
> > return true / false from #matches? so that will be one problem you
> > have. Try just hard-coding the #matches? method to return false and
> > see if you get one of your tests to fail.
> >
> > What are you imagining that #response is going to return in this
> > instance?
> Oh OK. Well what I want is to be able to test if that form exists on
> the page.
> So how would you recommend going about it otherwise? I tried putting a
> begin ... end block around it, but that doesn't seem to work either.
>     def matches? response, &block
>       @block ||= block
>       begin
>         response.should have_selector('form#%s' % [@id]) do |form|
>           !@block or @block.call form
>         end
>       rescue
>         false
>       else
>         true
>       end
>     end
> It still has an error, but now it's covered up by my failure_message. I
> output $! As a test, though, and it's the same error.
> Brandon

More information about the rspec-users mailing list