如何使用RSpec声明初始化行为?

Gle*_*min 5 ruby mocking rspec2

我有一个消息类,可以通过将参数传递给构造函数来初始化,或者通过不传递任何参数,然后使用访问器设置属性.在属性的setter方法中进行了一些预处理.

我有测试确保setter方法做他们应该做的事情,但我似乎无法找到一种测试初始化​​方法实际调用setter的好方法.

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
Run Code Online (Sandbox Code Playgroud)

小智 4

我倾向于测试初始化​​程序的行为,

即它按照您期望的方式设置变量。

不要陷入实际的操作方式中,假设底层访问器可以工作,或者如果您愿意,您可以设置实例变量。这几乎是一个很好的老式单元测试。

例如

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
Run Code Online (Sandbox Code Playgroud)