gpt4 book ai didi

ruby-on-rails - Rspec 测试比较<=>

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:12 26 4
gpt4 key购买 nike

我有一个使用 Comparable 的模型我已经实现了所需的 <=>为此的方法。我应该如何使用 rspec 进行测试? (我知道这不是 TDD,因为我已经实现了该方法)?

class Grade < ActiveRecord::Base
include Comparable
def <=>(other)
self.sort_key <=> other.sort_key
end
end

最佳答案

鉴于以下 Grade实现:

class Grade
attr_reader :sort_key
def initialize(sort_key)
@sort_key = sort_key
end
def <=>(other)
return nil unless other.respond_to?(:sort_key)
@sort_key <=> other.sort_key
end
end

我只是测试一下 Grade#<=>根据 documentation 的内容,行为正常对于 Object#<=>说:

# comparable_grade.spec
describe "Grade#<=>" do

it "returns 0 when both operands are equal" do
(Grade.new(0) <=> Grade.new(0)).should eq(0)
end

it "returns -1 when first operand is lesser than second" do
(Grade.new(0) <=> Grade.new(1)).should eq(-1)
end

it "returns 1 when first operand is greater than second" do
(Grade.new(1) <=> Grade.new(0)).should eq(1)
end

it "returns nil when operands can't be compared" do
(Grade.new(0) <=> Grade.new("foo")).should be(nil)
(Grade.new(0) <=> "foo").should be(nil)
(Grade.new(0) <=> nil).should be(nil)
end

it "can compare a Grade with anything that respond_to? :sort_key" do
other = double(sort_key: 0)
(Grade.new(0) <=> other).should eq(0)
end

end

关于ruby-on-rails - Rspec 测试比较<=>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17220120/

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