Ruby + Rspec:我应该如何测试 attr_accessor? [英] Ruby + Rspec: How should I be testing attr_accessor?

查看:28
本文介绍了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 的默认功能?或者我是否必须为每个属性单独和手动测试 getter 和 setter 的过程?

It seems a bit tedious since attr_accessor is used in practically every class. Is there a shortcut for this in rspec to test the default functionality of a getter and setter? Or do I have to go through the process of testing the getter and setter individually and manually for every attribute?

推荐答案

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

I created a custom rspec matcher for this:

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

然后在我的规范中,我像这样使用它:

Then in my spec, I use it like so:

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

这篇关于Ruby + Rspec:我应该如何测试 attr_accessor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆