stoerebink stoerebink - 4 months ago 16
Ruby Question

Rspec testing POROs included in models rails

In my Order model I include a PORO class "ShipmentHandler". This PORO is located like this: app/models/order/shipment_handler.rb

I invoke this in my Order model like so:

def assign_shipments
ShipmentHandler.new(self).assign_shipments
end


My PORO looks like:

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

def some_methods
end
end
end


I'm trying to create spec to test the methods in my ShipmentHandler class. I'm not sure how to do this as I keep getting errors like
uninitialized constant ShipmentHandler


I've tried to add it to my order_spec.rb like so:

describe Order do
describe Order::ShipmentHandler do
end
end


and:

describe Order do
describe ShipmentHandler do
end
end


Neither work. I've also tried creating a spec in spec/models/order/shipment_handler_spec.rb
This also failed.

Answer

The following way of writing specs worked for me when I made some assumptions on what your Order class looks like with the nested ShipmentHandler class:

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
Comments