[rspec-users] Newbie question with rspec on rails

Pat Maddox pergesu at gmail.com
Mon Feb 4 02:31:22 EST 2008


> What is the convention for naming and creating specs when speccing out cross object behaviour?

I missed this.  For stuff like mixins, I'll generally stick the module
definition under lib/ and have a corresponding spec under spec/lib.
Also I usually write the spec like

module NameableSpec
  class Person
    include Nameable
  end

  describe Nameable do
    before(:each) do
      @person = Person.new
      @person.set_name "Pat Maddox"
    end

    it "should parse the first name" do
      @person.first_name.should == "Pat"
    end

    it "should parse the last name" do
      @person.last_name.should == "Maddox"
    end
  end
end

The reason that I do that is because in order to write a spec for this
module, I have to actually mix it into a class.  I wrap the whole spec
in a module so that my test class name doesn't clash with any existing
class names.

Another way to do it is to define the class dynamically before each test:

describe Nameable do
  before(:each) do
    klass = Class.new { include Nameable }
    @person = klass.new
    @person.set_name "Pat Maddox"
  end

  it "should parse the first name" do
    @person.first_name.should == "Pat"
  end

  it "should parse the last name" do
    @person.last_name.should == "Maddox"
  end
end

The upside to that is that you don't have the ugly wrapper module.
The downside is that you can't easily reuse the class between describe
blocks - you'd still want to have a wrapper module to avoid polluting
the namespace.  I tend to prefer this dynamic class creation, because
it's usually less code.  I also end up with a bunch of little,
temporary helper classes that have only the behavior I want, rather
than a bigger test helper class with behavior to support multiple
specs.

I'm curious how other people handle this type of thing.

Pat


More information about the rspec-users mailing list