Sha256: 10ebdcf50ffc3296829b952a2ee2c051b453fbffa3b96bb7d29895fc45542e2a

Contents?: true

Size: 1.86 KB

Versions: 13

Compression:

Stored size: 1.86 KB

Contents

require 'rails_helper'
require 'sorbet-rails/model_rbi_formatter'

RSpec.describe SorbetRails::PluckToTStruct do
  let!(:harry) do
    Wizard.create!(
      name: 'Harry Potter',
      house: :Gryffindor,
    )
  end

  let!(:hermione) do
    Wizard.create!(
      name: 'Hermione Granger',
      house: :Gryffindor,
    )
  end

  class WizardName < T::Struct
    const :name, String

    def ==(other)
      return false unless other.is_a?(self.class)
      name == other.name
    end

    def eql?(other)
      self == other
    end
  end

  class WizardT < T::Struct
    const :name, String
    const :house, String

    def ==(other)
      return false unless other.is_a?(self.class)
      name == other.name && house == other.house
    end

    def eql?(other)
      self == other
    end
  end

  shared_examples 'pluck_to_tstruct' do |struct_type, expected_values|
    it 'plucks correctly from ActiveRecord model' do
      plucked = Wizard.pluck_to_tstruct(TA[struct_type].new)
      expect(plucked).to match_array(expected_values)
    end

    it 'plucks correctly from ActiveRecord relation' do
      plucked = Wizard.all.pluck_to_tstruct(TA[struct_type].new)
      expect(plucked).to match_array(expected_values)
    end
  end

  context 'pluck 1 attribute' do
    it_should_behave_like 'pluck_to_tstruct', WizardName, [
      WizardName.new(name: "Harry Potter"),
      WizardName.new(name: "Hermione Granger"),
    ]
  end

  context 'pluck multiple attributes' do
    it_should_behave_like 'pluck_to_tstruct', WizardT, [
      WizardT.new(name: "Harry Potter", house: "Gryffindor"),
      WizardT.new(name: "Hermione Granger", house: "Gryffindor"),
    ]
  end

  context 'given a wrong type' do
    it 'should raise error' do
      expect {
        plucked = Wizard.pluck_to_tstruct(TA[String].new)
      }.to raise_error(SorbetRails::PluckToTStruct::UnexpectedType)
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
sorbet-rails-0.7.0 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.5.1 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.5 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.4 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.3 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.2 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.1 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.6.0 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.5.9.1 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.5.9 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.5.8.1 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.5.8 spec/pluck_to_tstruct_spec.rb
sorbet-rails-0.5.7 spec/pluck_to_tstruct_spec.rb