加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:40:46 所属栏目:百科 来源:网络整理
导读:我有一个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 :chosenend 这似乎有点乏味,因为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) }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读