如何使用 RSpec 断言初始化行为?
我有一个消息类,可以通过将参数传递到构造函数中来初始化它,或者不传递参数,然后使用访问器设置属性。属性的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我倾向于测试初始化程序的行为,
即它如何设置您期望的变量。
不要陷入实际的操作方式中,假设底层访问器可以工作,或者如果您愿意,您可以设置实例变量。这几乎是一个很好的老式单元测试。
例如
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.