Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assert on initialize behaviour with RSpec?

I have a message class, which can be initialized by passing arguments into the constructor, or by passing no arguments and then setting the attributes later with accessors. There is some pre-processing going on in the setter methods of the attributes.

I've got tests which ensure the setter methods do what they're supposed to, but I can't seem to figure out a good way of testing that the initialize method actually calls the setters.

class Message
  attr_accessor :body
  attr_accessor :recipients
  attr_accessor :options

  def initialize(message=nil, recipients=nil, options=nil)
    self.body = message if message
    self.recipients = recipients if recipients
    self.options = options if options
  end

  def body=(body)
    @body = body.strip_html
  end
  def recipients=(recipients)
    @recipients = []
    [*recipients].each do |recipient|
      self.add_recipient(recipient)
    end
  end
end
like image 202
Glenjamin Avatar asked Oct 14 '22 18:10

Glenjamin


1 Answers

I would tend to test the behaviour of the initializer,

i.e. that its setup the variables how you would expect.

Not getting caught up in the actuality of how you do it, assume that the underlying accessors work, or alternatively you could set the instance variables if you wanted. Its almost a good old fashioned unit test.

e.g.

describe "initialize" do
  let(:body) { "some text" }
  let(:people) { ["Mr Bob","Mr Man"] }
  let(:my_options) { { :opts => "are here" } }

  subject { Message.new body, people, my_options }

  its(:message)    { should == body }
  its(:recipients) { should == people }
  its(:options)    { should == my_options }
end
like image 113
Jon Rowe Avatar answered Oct 18 '22 13:10

Jon Rowe