我有一个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_accessor
,所以看起来有点单调乏味。在rspec中是否有一个快捷方式来测试getter和setter的默认功能?或者我是否必须单独和手动为每个属性完成测试getter和setter的过程?
答案 0 :(得分:14)
我为此创建了一个自定义的rspec匹配器:
spec/custom/matchers/should_have_attr_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) }
答案 1 :(得分:11)
这是使用RSpec 3的上一个答案的更新版本,替换failure_message_for_should
的{{1}}和failure_message
的{{1}}:
failure_message_for_should_not