Rspec测试PORO包含在模型轨道中

时间:2016-07-25 11:10:47

标签: ruby-on-rails ruby ruby-on-rails-4 rspec

在我的订单模型中,我包含了一个PORO类" ShipmentHandler"。此PORO的位置如下:app / models / order / shipment_handler.rb

我在订单模型中调用了这个,如下所示:

def assign_shipments
  ShipmentHandler.new(self).assign_shipments
end

我的PORO看起来像:

class Order
    class ShipmentHandler 
        def initialize(order)
            @set_some_variables
        end

        def some_methods
        end
    end
end

我试图创建规范来测试ShipmentHandler类中的方法。我不确定如何执行此操作,因为我不断收到uninitialized constant ShipmentHandler

等错误

我试图将它添加到我的order_spec.rb中,如下所示:

describe Order do 
    describe Order::ShipmentHandler do
    end
end

和:

describe Order do 
    describe ShipmentHandler do
    end
end

都没有工作。我还尝试在spec / models / order / shipment_handler_spec.rb中创建规范 这也失败了。

1 个答案:

答案 0 :(得分:2)

当我对嵌套Order类的ShipmentHandler类看起来有些假设时,以下编写规范的方式对我有用:

class Order
  def assign_shipments
    ShipmentHandler.new(self).assign_shipments
  end

  class ShipmentHandler
    def initialize(order)
      @order = order
    end

    def some_methods
    end
  end
end

RSpec.describe Order do
  it { is_expected.to be_a Order }
end

# Method 1
RSpec.describe Order::ShipmentHandler do
  subject(:shipment_handler) { described_class.new(Order.new) }

  it { is_expected.to be_a Order::ShipmentHandler }
end

# Method 2
class Order
  RSpec.describe ShipmentHandler do
    subject(:shipment_handler) { described_class.new(Order.new) }

    it { is_expected.to be_a Order::ShipmentHandler }
  end
end