ruby - RSpec less strict equality expectation for test -
i have following test:
it "can add item" item = item.new("car", 10000.00) expect(@manager.add_item("car", 10000.00)).to eq(item) end
item's initialize looks (class has attr_accessor for, type, price, , is_sold):
def initialize(type, price) @type = type @price = price @is_sold = false @@items << self end
manager's add item looks like:
def add_item(type, price) item.new(type, price) end
this test failing because 2 items have different object ids, although attributes identical. item's initialize method takes type, , price. want check equality on features... there way test strictly attribute equality?
i have tried should be, should eq, be, , eql? no luck.
assuming class has public interface reading attributes (e.g. attr_reader :type, :price
), sensible way implement ==
method:
class item # ... def ==(other) self.type == other.type && self.price == other.price end end
this allows 2 items compared using ==
, , rspec's eq
method work expected.
if don't want class have equality method, best bet check each attribute individually:
it "can add item" expected = item.new("car", 10000.00) actual = @manager.add_item("car", 10000.00) expect(actual.type).to eq(expected.type) expect(actual.price).to eq(expected.price) end
but can tell may become maintainability challenge add features item.
Comments
Post a Comment