2014-06-26 126 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