[rspec-users] How best to write repetitive specs

Zach Dennis zach.dennis at gmail.com
Thu Jan 22 07:47:44 EST 2009


On Thu, Jan 22, 2009 at 6:32 AM, Zac Zheng <lists at ruby-forum.com> wrote:
> I wanted to test that my mailer models all had the correct headers:
> subject, to and from fields.
>
> I had done this by creating this in my spec_helper.rb:
>
> module TestMailerHelpers
>  module ClassMethods
>    def test_basic_headers
>      it "subject" do
>        @email.subject.should_not be_blank
>      end
>
>      it "to email address(es)" do
>        @email.to.should_not be_blank
>      end
>
>      it "from email address(es)" do
>        @email.from.should_not be_blank
>      end
>    end
>  end
>
>  def self.included(receiver)
>    receiver.extend         ClassMethods
>    receiver.fixtures :users
>    receiver.fixtures :roles
>    receiver.fixtures :roles_users
>    receiver.fixtures :ports
>  end
> end
>

Check out shared_examples_for:
http://rspec.rubyforge.org/rspec/1.1.12/classes/Spec/DSL/Main.html#M000505

shared_examples_for "a standard mailer model" do
  # ...
end

I usually put my shared examples in spec/shared_examples/ and then in
your actual mailer models you'd add the below line...

describe YourMailerModel do
   it_should_behave_like "a standard mailer model"
end


>
> I included the above in all my mailer specs, for which there are four,
> and called the method 'test_basic_headers'. This used to work, even
> though it looks terribly unDRY.
>
> An example of a mailer spec:
>
> require File.dirname(__FILE__) + '/../spec_helper'
> describe UserMailer do
>  include TestMailerHelpers
>
>  before(:each) do
>    @user = users(:normal)
>    @port = ports(:Alexandria)
>  end
>
>  describe "activation" do
>    before(:each) do
>      @email = UserMailer.create_activation(@user)
>    end
>
>    test_basic_headers
>  end
>  # ...
> end
>
> I have two problems.
>
> One, I am now receiving 'test_basic_headers' method not found error
> after upgrading rspec to 1.1.12. UserMailer is not including
> TestMailerHelpers correctly. Can anyone see why?
>
> Problem number two is that I have realised this is do doubt in
> inefficient way of doing what I want. Can anyone recommend a better way?
>
> Much thanks,
> Zac
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>



-- 
Zach Dennis
http://www.continuousthinking.com
http://www.mutuallyhuman.com


More information about the rspec-users mailing list