[rspec-users] should_raise ain't workin' with the `spec` command

Matt Wynne matt at mattwynne.net
Sat Nov 8 02:22:09 EST 2008

On 8 Nov 2008, at 06:29, David Beckwith wrote:
> Hello my fellow RSpeckers,
> I am using the spec command like this:
>                spec tokyo_record_spec.rb
> And the for some reason the should_raise Rspec command is not
> happening with my lambda block:
>    it "should raise a NoSuchAttribute error if the attribute 'name'
> hasn't been declared yet and you try to create a persisted instance of
> the object." do
>      lambda {
>        User.create( :name => 'Dustin')
>      }. should_raise( NoSuchAttribute )
>    end
> Here is the error:
> undefined method `should_raise' for #<Proc:0x006fc7a0 at ./
> tokyo_record_spec.rb:77>
> ./tokyo_record_spec.rb:77:

Okay the the first obvious problem is you've got the syntax wrong for  
asserting an exception. And you wouldn't be the first - I keep  
forgetting this myself as I don't do it very often.

Try this instead:
    lamda { do_bad_stuff }.should raise_error

Also, are you calling require 'spec' at the top of your spec file?  
That's what will ensure that the Proc object is patched with a #should  

> I'm not sure how the `spec` command actually works, and I'm sure
> that's at least one source of my confusion.  Also, I don't know where
> `should_raise` is defined either.  If anybody could help me clear the
> clouds in my brain, I would greatly appreciate it.  Please point me in
> a sunnier direction.

You can use ruby tokyo_record_spec.rb or spec tokyo_record_spec.rb at  
the command line to run your specs - both are valid, but spec will  
give you some more options to format your output in different ways  
etc. that start to become more useful as you write more specs. For now  
it might feel simpler to just call your specs using the ruby command.

> This is straight Ruby code.  It has nothing to do with Rails. My
> directory structure looks something like this:
> /tokyo
> /tokyo/tokyo_record.rb
> /tokyo/tokyo_record_spec.rb
> And at the top of /tokyo/tokyo_record_spec.rb I have only require
> 'tokyo_record' which is a homemade Ruby module that I'm trying to spec
> with RSpec.

It's pretty conventional to use a spec_helper.rb file somewhere that  
you just always require at the top of each spec file. That gives you  
an extensibility point if you want to do any global setup of your test  
environment that has to run before each set of spec. Also most people  
seem to keep their specs in a separate 'spec' directory. If you want  
to use tools like RSpactor you'd need to stick to this convention (for  
now at least).

It might be worth creating a vanilla rails project, adding the rspec- 
rails gem, and running 'script/generate rspec' in there just to see  
how it's done - the examples are pretty good and give you a good idea  
of the conventions other people are using.


More information about the rspec-users mailing list