【问题标题】:Rspec test Comparable <=>Rspec 测试可比 <=>
【发布时间】:2013-06-17 16:37:00
【问题描述】:

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

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

【问题讨论】:

  • 在编写测试之前,我不会因为编写这样一个微不足道的方法而自责。重要的是要有测试,而不一定是你是如何得到它们的。
  • 即使它是微不足道的,我仍然想看看人们会如何测试它,因为我是测试新手。
  • 我的意思是你写了一个方法,这没什么大不了的,不像写一个大型应用程序然后然后尝试编写测试。

标签: ruby-on-rails ruby rspec mocking stub


【解决方案1】:

鉴于以下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#&lt;=&gt; 的行为是否正常,根据documentation for Object#&lt;=&gt; 所说的:

# 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

【讨论】:

    【解决方案2】:

    使用存根进行测试。快速简单。

    describe Grade do
      context "<=>" do
        before do
          g1 = Grade.new
          g2 = Grade.new
          g3 = Grade.new
          g1.stub(:sort_key=>1)
          g2.stub(:sort_key=>2)
          g3.stub(:sort_key=>1)
        end
    
        it "calls sort_key" do
          Grade.any_instance.should_receive(:sort_key)
          g1 < g2
        end
    
        it "works for comparing" do
          expect{g1<g2}.to be_true
          expect{g2>g1}.to be_true
          expect{g1=g3}.to be_true
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-26
      • 2011-06-09
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 2014-05-18
      相关资源
      最近更新 更多