2014-06-26 3 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 индивидуально и вручную для каждого атрибута?

+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_should на failure_message и failure_message_for_should_not на failure_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 
Смежные вопросы