[rspec-users] Another "how do I spec this?"

David Chelimsky dchelimsky at gmail.com
Mon Jan 1 09:16:05 EST 2007


On 1/1/07, Pat Maddox <pergesu at gmail.com> wrote:
> I wanted to add a convenience method on my User class to see if he was
> already signed up for a tournament.  Here's my spec
>
> context "A User signed up for one tournament" do
>   setup do
>     @t1 = Tournament.new
>     @t1.save false
>     @t2 = Tournament.new
>     @t2.save false
>     @user = User.new
>     @user.save false
>     @user.registrations << Registration.new(:tournament => @t1)
>   end
>
>   specify "should be signed up for that tournament" do
>     @user.should_be_signed_up_for @t1
>   end
>
>   specify "should not be signed up for another tournament" do
>     @user.should_not_be_signed_up_for @t2
>   end
> end
>
> class User < ActiveRecord::Base
>   has_many :registrations
>
>   def signed_up_for?(tournament)
>     !registrations.find_by_tournament_id(tournament).nil?
>   end
> end
>
> Are there any potential improvements, or is that the best way to spec it?

Couple of thoughts. Creating new unvalidated models seems to be
something useful, so...

module ModelSpecUtils
  def unvalidated_model(klass)
    model = klass.new
    model.save(false)
    model
  end
end

Also, this line:

@user.registrations << Registration.new(:tournament => @t1)

is breaking encapsulation a bit. Given that and the utility module
above, I might end up w/ something like this:

context "A User signed up for one tournament" do
  include ModelSpecUtils

  setup do
    @tournament1 = unvalidated_model(Tournament)
    @tournament2 = unvalidated_model(Tournament)
    @user = unvalidated_model(User)
    @user.register_for(@tournament1)
  end

  specify "should be signed up for that tournament" do
    @user.should_be_signed_up_for @tournament1
  end

  specify "should not be signed up for another tournament" do
    @user.should_not_be_signed_up_for @tournament2
  end
end

David

>
> Pat
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list