2014-06-26 28 views
14

我有ReturnItem类。Ruby + Rspec:我应该如何测试attr_accessor?

规格:

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

你会认为这是核心Rspec/Shoulda库的一部分,呃? –

回答

10

我创建了这个自定义的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) } 
+0

我真的很喜欢你匹配的简单。将它添加到我的代码中我感觉更舒适。对于还处理'attr_reader'和'attr_writer'的更彻底的匹配器,请查看https://gist.github.com/daronco/4133411#file-have_attr_accessor-rb –

9

这其中的一个更新版本使用RSpec 3的上一个答案,替换failure_message_for_shouldfailure_messagefailure_message_for_should_notfailure_message_when_negated

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