# Rspec model class methods

**URL:** <https://www.ruby-forum.com/t/rspec-model-class-methods/135501>\
**Category:** Rails\
**Created:** [April 22, 2008, 6:41pm UTC](https://www.ruby-forum.com/t/rspec-model-class-methods/135501 "2008-04-22T18:41:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![adammontgomery](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ce7236/32.png) [@adammontgomery](https://www.ruby-forum.com/u/adammontgomery)\
**Post date:** [April 22, 2008, 6:41pm UTC](https://www.ruby-forum.com/t/rspec-model-class-methods/135501/1 "2008-04-22T18:41:03Z")

</div>

I’ve started specifying a project and could use some help. I’m not sure  
if the spec is entirely necessary, it would be great to get some  
guidance on a best practice or something close.

I recently realized the need to add the method below grouped\_by\_months  
and started to write a spec.

idea 1:  
{{{  
before do  
@comment = Comment.new  
@comment.stub!(:created\_at).and\_return(Time.now -2.days)  
end

it ‘should return comments grouped by month’ do  
group\_terms = lambda{|comment| comment.created\_at.beginning\_of\_month  
}

```
Comment.should_receive(:find).and_return([@comment])
[@comment].should_receive(:group_by).with(&group_terms).and_return([[@comment]])

Comment.grouped_by_month

```

end  
}}}

idea 2  
{{{

before do  
@comment = Comment.new  
@comment.stub!(:created\_at).and\_return(Time.now -2.days)  
end

it ‘should return comments grouped by month’ do  
group\_terms = lambda{|comment| comment.created\_at.beginning\_of\_month }  
lambda{  
Comment.should\_receive(:find).and\_return([@comment])  
}.should\_receive(:group\_by).with(&group\_terms)

Comment.grouped\_by\_month  
end  
}}}

Class with method  
{{{  
class Comment \< ActiveRecord::Base

validates\_presence\_of :email, :body  
validates\_format\_of :email, :with =\>  
/\A([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})\Z/i, :message =\> ‘invalid  
email address’

def self.grouped\_by\_month  
find(:all).group\_by{|comment| comment.created\_at.beginning\_of\_month  
}  
end

end  
}}}
