require 'rails_helper'

RSpec.describe Dunlop::UserFiltersController do
  routes { Dunlop::Engine.routes }
  let(:model) { Dunlop::UserFilter }
  describe 'logged in' do
    let(:user) { create :user }
    before { sign_in user}
    describe '#index' do
      it "returns listed serialized" do
        model1 = create 'dunlop/user_filter', user: user, scope_key: 'panda/action-list', filters: {key_with_underscores: 17}
        model2 = create 'dunlop/user_filter', user: user, scope_key: 'other/action-list', filters: {key_with_underscores: 19}
        get :index, params: {q: {scope_key_matches: 'panda/%'}}

        response.body.should start_with '{"data":['
        result = JSON.parse(response.body)['data']
        result.should eq [
          {"id"=>model1.id.to_s, "type"=>"dunlop/user-filter", "attributes"=>{"scope-key"=>"panda/action-list", "filters"=>{"key_with_underscores"=>17}, "is-default"=>false}}
        ]
      end
    end

    describe '#create' do
      it 'creates a new filter attached to the current user' do
        post :create, params: {'dunlop/user_filter' => {scope_key: 'panda/something', filters: {abc_def: 'g'}, is_default: true}}
        record = model.last
        record.user.should eq user
        record.scope_key.should eq 'panda/something'
        record.filters.should eq('abc_def' => 'g')
        record.should be_is_default
      end
    end

  end

  describe 'not logged in' do
    describe '#index' do
      it "302" do
        model = create 'dunlop/user_filter', scope_key: 'panda:action-list', filters: {key_with_underscores: 17}
        get :index
        response.body.should include 'redirected'
        response.body.should include 'users/sign_in'
      end
    end
  end
end
