[rspec-users] Accessing the model class from within an rspec-rails spec

Mike Gunderloy MikeG1 at larkfarm.com
Wed Oct 29 07:23:46 EDT 2008

Part of the testing harness on one of our projects:

module Spec::Example::ExampleGroupMethods
   def model

   def should_require(*attrs)
     raise "should require needs at least one attribute" if attrs.empty?
     model = model()
     attrs.each do |attribute|
       it "should require :#{attribute}" do
         m = Factory.build(model.to_sym)
         m.send("#{attribute}=", nil)
         m.should have(1).error_on(attribute)

Using FactoryGirl for spinning up instances, but of course easily  
tweaked for other mocking.


On Oct 28, 2008, at 8:09 AM, Cameron Booth wrote:

> Hi everybody,
> New to the list, so apologies if this has been answered elsewhere,  
> but I didn't find it. I'm trying to build up a plugin of useful  
> rspec macros for rails development, eg. things like:
> it_should_return_success
> it_should_redirect_to { some_url }
> I'm basing my ideas off of some stuff technoweenie has done, as well  
> as a few others.
> One thing I'd love to do is be able to figure out the model class in  
> a rails model spec, so I can do something like:
> describe User do
>   it_should_validate_presence_of :name
> end

More information about the rspec-users mailing list