rails attr_reader attr_accessor rspec

attr_reader - Ruby+Rspec: ¿Cómo debería probar attr_accessor?



attr_reader rails 5 (2)

Esta es una versión actualizada de la respuesta anterior usando RSpec 3, reemplazando failure_message_for_should por failure_message y failure_message_for_should_not por 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

Tengo una clase ReturnItem .

especificaciones:

require ''spec_helper'' describe ReturnItem do #is this enough? it { should respond_to :chosen } it { should respond_to :chosen= } end

clase:

class ReturnItem attr_accessor :chosen end

Parece un poco tedioso ya que attr_accessor se usa en prácticamente todas las clases. ¿Hay un atajo para esto en rspec para probar la funcionalidad predeterminada de un getter y setter? ¿O tengo que pasar por el proceso de probar el getter y el setter individualmente y manualmente para cada atributo?


He creado un emparejador rspec personalizado para esto:

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

Entonces en mi especificación, lo uso así:

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