Ruby Rspec:我应该如何测试attr_accessor?

前端之家收集整理的这篇文章主要介绍了Ruby Rspec:我应该如何测试attr_accessor?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个ReturnItem类

眼镜:

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的默认功能?或者我必须单独和手动地对每个属性进行检测和设置过程?

解决方法

我为此创建了一个自定义rspec匹配器:

规格/自定义/匹配器/ 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) }
原文链接:https://www.f2er.com/ruby/271658.html

猜你在找的Ruby相关文章