|
| 1 | +module ForestLiana |
| 2 | + describe SerializerFactory do |
| 3 | + describe '#serializer_for has_one_relationships patch' do |
| 4 | + let(:user) { User.create!(name: 'PatchTest') } |
| 5 | + let(:island) { Island.create!(name: 'TestIsland') } |
| 6 | + let(:tree) { Tree.create!(name: 'TestTree', island: island, owner: user) } |
| 7 | + |
| 8 | + it 'simulates has_one relation with only primary key' do |
| 9 | + factory = described_class.new |
| 10 | + serializer_class = factory.serializer_for(Tree) |
| 11 | + |
| 12 | + serializer_class.send(:has_one, :island) { } |
| 13 | + |
| 14 | + instance = serializer_class.new(tree, fields: { |
| 15 | + 'Island' => [:id], |
| 16 | + 'Tree' => [:island] |
| 17 | + }) |
| 18 | + |
| 19 | + relationships = instance.send(:has_one_relationships) |
| 20 | + expect(relationships).to have_key(:island) |
| 21 | + relation_data = relationships[:island] |
| 22 | + expect(relation_data[:attr_or_block]).to be_a(Proc) |
| 23 | + model = relation_data[:attr_or_block].call |
| 24 | + |
| 25 | + expect(model).to be_a(Island) |
| 26 | + expect(model.id).to eq(island.id) |
| 27 | + end |
| 28 | + |
| 29 | + it 'returns nil if foreign key is nil' do |
| 30 | + tree_without_island = Tree.create!(name: 'NoIslandTree', island_id: nil, owner: user) |
| 31 | + |
| 32 | + factory = described_class.new |
| 33 | + serializer_class = factory.serializer_for(Tree) |
| 34 | + |
| 35 | + serializer_class.send(:has_one, :island) { } |
| 36 | + |
| 37 | + instance = serializer_class.new(tree_without_island, fields: { |
| 38 | + 'Island' => [:id], |
| 39 | + 'Tree' => [:island] |
| 40 | + }) |
| 41 | + |
| 42 | + relationships = instance.send(:has_one_relationships) |
| 43 | + expect(relationships).to have_key(:island) |
| 44 | + relation_data = relationships[:island] |
| 45 | + expect(relation_data[:attr_or_block]).to be_a(Proc) |
| 46 | + model = relation_data[:attr_or_block].call |
| 47 | + |
| 48 | + expect(model).to be_nil |
| 49 | + end |
| 50 | + |
| 51 | + end |
| 52 | + end |
| 53 | +end |
0 commit comments