Why Entity.new does not set attributes?

Hi there!

Entities are supposed to be very simple struct-like objects, and they use Dry::Struct under the hood.

I guess it’s reasonable, that I expect the initialization can happen in the similar way.

However, MyEntity.new(attributes) does not set any attributes.

module Entities
  class Foo < ROM::Struct
  end
end

foo = Entities::Foo.new(id: 1)
# => #<Entities::Foo>

foo.attributes
# => {}

Usecase:
I want to write tests to my Entity objects (Or rather adjust existing tests after ROM upgrade).

Version: ROM 5.2.6

I know Structs are supposed to be loaded by Relations, but still - I guess it would be useful to test them if there are custom methods defined.

I do use rom-factory, and I tried to check the source code how this problem is solved there, but could not figure it out yet.

2 Likes

This will be improved in rom 6.0.0. Notice that Entities::Foo is not actually the struct class that’s gonna be used. rom generates struct sub-classes for each unique schema that you use. ie users.select(:id, :name) doesn’t create instances of User entity but its subclass that only has id and name attributes defined. This is going to be changed so that the canonical class is also the one with the default schema.

2 Likes

@swilgosz: For now you could go with:

describe Entities::Entity do
  let(:described_class) { App["repositories.entities_repo"].entities.mapper.model }
  let(:subject) do
    described_class.new(id: 1, first_name: 'Michael', last_name: "Knight")
  end

  describe "#full_name" do
    it "should return its full_name" do
     expect(subject.full_name).to eq("Michael Knigth")
    end
  end
end
3 Likes