[rspec-devel] More DRY in descriptions

David Chelimsky dchelimsky at gmail.com
Wed May 16 21:13:26 EDT 2007


On 5/16/07, Evgeny <evgeny.zislis at gmail.com> wrote:
> Greetings All,
>
> I have been writing some code with rSpec (0.9.x) for a new project,
> and I notice that there is a thing I keep repeating myself on.
>
> Best shown in a short example:
>
>  describe ClassNameForSomeUser, "when first created" do
>   it "should fail when no name provided" do
>     lambda { ClassNameForSomeUser.new(:name => nil) }.should
> raise_error(ArgumentError, "No name provided")
>   end
>   it "should fail when something else is wrong" do
>     lambda { ClassNameForSomeUser.new(:wrongparam => true) }.should
> raise_error SomethingBad
>    end
> end
>
> naturally there are many more descriptions in there, so to make it just a
> little bit more DRY I did this:
>
>  describe ClassNameForSomeUser, "when first created" do
>   before(:each) do
>      @UCN = ClassNameForSomeUser
>   end
>    it "should fail when no name provided" do
>      lambda { @UCN.new(:name => nil) }.should raise_error(ArgumentError, "No
> name provided")
>    end
>    it "should fail when something else is wrong" do
>      lambda { @UCN.new(:wrongparam => true) }.should raise_error
> SomethingBad
>    end
>  end
>
> But then I notice that when I write "describe" I specify the class name
> already, so why not use it in some way?
> Is it possible to do something like :
>
>  describe ClassNameForSomeUser, "when first created" do
>   it "should fail when no name provided" do
>      lambda { this_class.new(:name => nil) }.should
> raise_error(ArgumentError, "No name provided")
>    end
>    it "should fail when something else is wrong" do
>      lambda { this_class.new(:wrongparam => true) }.should raise_error
> SomethingBad
>    end
>  end
>
> is this possible, or anything similar?

Anything's possible, but don't think I'd like to see this added to
RSpec. It's not really DRYing things up that much and, in larger
examples, will just make things more difficult to understand IMO.

I've written about this before - DRY is important, but in tests it is
not as important as clarity. The reasons that DRY is useful in subject
code don't all apply in tests. DRY is much more about objects than it
is about typing a few less variables here and there, and tests are
procedural. They might be expressed in objects, but they are still
procedures.

FWIW.

David

>
> Regards,
>
> - evgeny
>
> _______________________________________________
> rspec-devel mailing list
> rspec-devel at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-devel
>


More information about the rspec-devel mailing list