2014-06-26 6 views
14

मेरे पास ReturnItem कक्षा है।रुबी + रुपेक: मुझे 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 में इसके लिए शॉर्टकट है? या क्या मुझे प्रत्येक विशेषता के लिए व्यक्तिगत रूप से और मैन्युअल रूप से गेटर और सेटटर का परीक्षण करने की प्रक्रिया से गुजरना है?

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 

तब मेरे कल्पना में, मैं यह इसलिए की तरह उपयोग करें::

+0

आपको लगता है कि यह कोर रुपेक/कंधा पुस्तकालयों का हिस्सा है, आह? –

उत्तर

10

मैं इस के लिए एक कस्टम rspec मिलान बनाया

subject { described_class.new } 
it { should have_attr_accessor(:foo) } 
+0

मुझे वास्तव में आपके matcher की सादगी पसंद है। मैं इसे अपने कोड में जोड़ने में ज्यादा आरामदायक हूं। एक अधिक गहन मैचर के लिए जो 'attr_reader' और' attr_writer 'को भी संभालता है, https://gist.github.com/daronco/4133411#file-have_attr_accessor-rb पर एक नज़र डालें –

9

यह एक अद्यतन संस्करण है failure_message और failure_message_for_should_notfailure_message_when_negated के लिए failure_message_for_shouldfailure_message_for_should के लिए failure_message_for_should को प्रतिस्थापित करने का पिछला उत्तर:

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 
संबंधित मुद्दे