无法在 RSpec 中的模块内测试 class

Can't test class within a module in RSpec

我正在学习 RSpec,似乎在使用教程之外的任何代码时都惨遭失败。这就是为什么我用这个问题撞墙的原因。希望大家帮帮忙

lib/NegotiGate

module NegotiGate
  class Negotiation

    def initialize(price1, price2)
      @price1 = price1
      @price2 = price2
    end

    def both_prices_equal?(price1, price2)
      if @price1 == @price2
        true
      else
        false
      end
    end

  end
end

spec/NegotiGate_spec.rb

describe NegotiGate do

  before(:each) do
    @negotiate = Negotiation.new(10,10)
  end

  describe "Negotiation" do
    describe ".both_prices_equal?" do
      context "given the sellers price is the same as the buyers highest buying price" do
        it 'returns true' do
          expect(@negotiate.both_prices_equal?).to be_true
        end
      end
    end
  end
end

输出:

NegotiGate
  Negotiation
    .both_prices_equal?
      given the sellers price is the same as the buyers highest buying price
        returns true (FAILED - 1)

Failures:

  1) NegotiGate Negotiation .both_prices_equal? given the sellers price is the same as the buyers highest buying price returns true
     Failure/Error: @negotiate = Negotiation.new(10,10)

     NameError:
       uninitialized constant Negotiation
     # ./spec/NegotiGate_spec.rb:6:in `block (2 levels) in <top (required)>'

Finished in 0.00134 seconds (files took 0.15852 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/NegotiGate_spec.rb:11 # NegotiGate Negotiation .both_prices_equal? given the sellers price is the same as the buyers highest buying price returns true

非常感谢 TDD 学生的任何帮助。 干杯!

试试 NegotiGate::Negotiation.new

describe RSpec 中的块不影响 Ruby 命名空间。在您的规范中,您需要在任何地方都将 Negotiation 称为 NegotiGate::Negotiation

但是,您在该规范中真正描述的不是 NegotiGate 而是 NegotiGate::Negotiation,因此将 describe 块更改为 describe NegotiGate::Negotiation 然后您可以使用described_class 简称:

describe NegotiGate::Negotiation do
  before(:each) do
    @negotiate = described_class.new(10,10)
  end

  describe ".both_prices_equal?" do
    context "given the sellers price is the same as the buyers highest buying price" do
      it 'returns true' do
        expect(@negotiate.both_prices_equal?).to be_true
      end
    end
  end
end

顺便说一句,查看 RSpec 的 let,这是定义在多个测试中使用的变量的现代方法。实际上,在您展示的内容中,您应该只在示例中声明一个局部变量,但您可能会编写更多测试,然后值得定义 negotiate 一次。哦,将它命名为 negotiation 以匹配 class 名称会比 negotiate.

更好