require 'spec_helper'

RSpec.describe Clique::DataArray do
  subject { described_class.new(text) }
  let(:text) { double }
  let(:json) { double }

  before do
    allow(json).to receive(:map) { json }
    allow(JSON).to receive(:parse).with(text) { json }
  end

  describe '#initialize' do
    let(:instance) { described_class.new(text) }

    it 'parses given JSON text' do
      described_class.new(text)
      expect(JSON).to have_received(:parse).with(text)
    end

    it 'sets array instance variable' do
      expect(instance.instance_variable_get(:@array)).to eq json
    end
  end

  describe '#fields' do
    let(:john) { double(keys: %w[foo bar]) }
    let(:jane) { double(keys: %w[bar buz]) }
    let(:array) { [john, jane] }

    before do
      subject.instance_variable_set(:@array, array)
    end

    it 'returns unique fields in array of hashes' do
      expect(subject.fields).to eq %w[foo bar buz]
    end
  end

  describe '#each' do
    let(:items) { [double(foo: nil), double(foo: nil)] }

    before do
      subject.instance_variable_set(:@array, items)
      subject.each(&:foo)
    end

    it 'enumerates each item in array' do
      expect(items).to all(have_received(:foo))
    end
  end

  describe '#find_by' do
    let(:matched) { double(matches?: true) }
    let(:unmatched) { double(matches?: false) }
    let(:array) { [matched, unmatched] }

    before do
      subject.instance_variable_set(:@array, array)
    end

    it 'returns record matches the filters' do
      expect(subject.find_by('foo' => 3)).to eq([matched])
    end
  end
end
