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) }

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...