gpt4 book ai didi

rspec - ruby + Rspec : How should I be testing attr_accessor?

转载 作者:行者123 更新时间:2023-12-02 05:09:36 25 4
gpt4 key购买 nike

我有一个 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?

最佳答案

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

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

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

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

关于rspec - ruby + Rspec : How should I be testing attr_accessor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24434381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com