I am trying to test #initialize of class Author
:
# lib/author.rb
class Author
attr_reader :name, :filename, :website
def initialize(name, filename, website)
@name = name
@filename = filename
set_filename_from_name if filename == :auto
@website = website
end
end
In reality there are 8-9 properties of Author
, not just 3 and I've decided to require them all in #initialize.
I am trying to dry up my specs, but I have lots of repetitions.
I have created a helper module:
#spec/helpers/create_author.rb
module CreateAuthor
# Creates author with default values except for those listed
# under params.
def create_author(params = {})
defaults = {
name: "Ford",
filename: "Ford",
website: 'www.ford.com'
}
opt = defaults.merge(params)
Author.new(opt[:name],
opt[:filename],
opt[:website])
end
end
But now I have untested code which I need to test. This is spec for that helper method:
# spec/authors_helper_spec.rb
require_relative 'helpers/create_author'
describe 'Create Author Helper' do
# subject do
# Class.new { include CreateAuthor }
# end
include CreateAuthor
let(:defaults) do
{
name: "Ford",
filename: "Ford",
website: 'www.ford.com'
}
end
describe '#create_author' do
it 'returns author with default values when called with no parameters' do
author = create_author()
expect(author.class).to eq(Author)
expect(author.name).to eq(defaults[:name])
expect(author.filename).to eq(defaults[:filename])
expect(author.website).to eq(defaults[:website])
end
it 'returns author with custom name when specified' do
author = create_author(name: 'New Name')
expect(author.class).to eq(Author)
expect(author.name).to eq('New Name')
expect(author.filename).to eq(defaults[:filename])
expect(author.website).to eq(defaults[:website])
end
end
end
I will need to do similar thing for other class, so I will just change create_author(options={})
to create_class(class, options={})
and test that.
How can I DRY this up and make it less verbose?