require 'rails_helper'

describe MembersController, type: :controller do
  let(:admin) { create :admin }
  let(:member) { create :member }

  describe "member" do

    before (:each) do
      sign_in member.user
    end

    describe "GET 'show'" do

      it "should be successful" do
        get :show, params: { id: member.id }
        expect(response).to be_success
      end

      it "should find the right member" do
        get :show, params: { id: member.id }
        expect(assigns(:member)).to eq(member)
      end

    end

  end

  describe "admin" do

    before (:each) do
      sign_in admin.user
    end

    describe "edit" do
      it "should be successful" do
        get :edit, params: { id: admin.id }
        expect(response).to be_success
      end
    end

    describe "DELETE destroy" do
      before(:each) do
        create :member_status, active: false, name: "Inactive"
      end

      it "destroys the requested member" do
        another = create(:member)

        @request.env['HTTP_REFERER'] = members_path
        expect {
          delete :destroy, params: { id: another.to_param }
        }.to change(Member, :count).by(-1)
      end

      it "can't destroy but can deactivate" do
        another = create(:member)
        expect(another.member_status.active).to be

        Audited::Audit.as_user(another) do
          member.update!(first_name: "Foo")
        end

        @request.env['HTTP_REFERER'] = members_path
        delete :destroy, params: { id: another.to_param }

        another.reload
        expect(another.member_status.active).to_not be
        expect(response).to redirect_to(members_path)
      end

      context 'did not destroy, coming from member show' do
        before do
          expect_any_instance_of(Member).to receive(:destroy).and_return(false)
        end

        it "returns back" do
          @request.env['HTTP_REFERER'] = member_path(member)
          delete :destroy, params: { id: member.to_param }
          expect(response).to redirect_to(member_path(member))
        end
      end
    end

  end

end
