How best to write repetitive specs


#1

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

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


#2

How stupid of me! I was looking at the wrong spec file. My 1st problem
with no method found has now been solved.

If anyone can still recommend a better way of spec’ing these tests,
that’d be great.

Zac Z. wrote:

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?


#3

Thanks Zach(great name btw)!

I am using it now and it works great.


#4

On Thu, Jan 22, 2009 at 6:32 AM, Zac Z. removed_email_address@domain.invalid wrote:

 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

test_basic_headers
Problem number two is that I have realised this is do doubt in


Zach D.
http://www.continuousthinking.com
http://www.mutuallyhuman.com