如何使用 RSpec 断言初始化行为?

发布于 2024-10-12 16:42:24 字数 650 浏览 3 评论 0原文

我有一个消息类,可以通过将参数传递到构造函数中来初始化它,或者不传递参数,然后使用访问器设置属性。属性的 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞慾 2024-10-19 16:42:24

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

即它如何设置您期望的变量。

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

例如

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文