Ruby+;Rspec:我应该如何测试attr_访问器?
我有一个Ruby+;Rspec:我应该如何测试attr_访问器?,rspec,Rspec,我有一个ReturnItem类 规格: require 'spec_helper' describe ReturnItem do #is this enough? it { should respond_to :chosen } it { should respond_to :chosen= } end 类别: class ReturnItem attr_accessor :chosen end 这似乎有点乏味,因为几乎每个类都使用了attr\u访问器。在rspec中是否
ReturnItem
类
规格:
require 'spec_helper'
describe ReturnItem do
#is this enough?
it { should respond_to :chosen }
it { should respond_to :chosen= }
end
类别:
class ReturnItem
attr_accessor :chosen
end
这似乎有点乏味,因为几乎每个类都使用了
attr\u访问器。在rspec中是否有测试getter和setter的默认功能的快捷方式?或者我必须对每个属性分别手动测试getter和setter吗?我为此创建了一个自定义rspec匹配器:
spec/custom/matchers/should\u have\u attr\u accessor.rb
RSpec::Matchers.define :have_attr_accessor do |field|
match do |object_instance|
object_instance.respond_to?(field) &&
object_instance.respond_to?("#{field}=")
end
failure_message_for_should do |object_instance|
"expected attr_accessor for #{field} on #{object_instance}"
end
failure_message_for_should_not do |object_instance|
"expected attr_accessor for #{field} not to be defined on #{object_instance}"
end
description do
"checks to see if there is an attr accessor on the supplied object"
end
end
然后在我的规范中,我这样使用它:
subject { described_class.new }
it { should have_attr_accessor(:foo) }
这是使用RSpec 3的上一个答案的更新版本,在\u否定时,将\u应
的故障消息\u替换为故障消息\u,而不应
的故障消息\u替换为故障消息\u
:
RSpec::Matchers.define :have_attr_accessor do |field|
match do |object_instance|
object_instance.respond_to?(field) &&
object_instance.respond_to?("#{field}=")
end
failure_message do |object_instance|
"expected attr_accessor for #{field} on #{object_instance}"
end
failure_message_when_negated do |object_instance|
"expected attr_accessor for #{field} not to be defined on #{object_instance}"
end
description do
"assert there is an attr_accessor of the given name on the supplied object"
end
end
我真的很喜欢你的媒人的简单。我更愿意将它添加到我的代码中。对于一个更全面的匹配器,它也可以处理attr\u reader
和attr\u writer
看看,我相信它已经成为任何库的一部分,我们可以使用它。更新的答案将不胜感激。你会认为这是核心Rspec/Shoulda库的一部分,是吗?