require 'rails_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator.  If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails.  There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec.  Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.

RSpec.describe TenantsController, type: :controller do

  let(:valid_attributes) {
    {name: "nt001",
     company_name: "カンパニー",
     bpuse_flg: "1",
     user_email: "nt001@useremail.com",
     user_name: "USER",
     password: "pass1234",
     password_confirmation: "pass1234"
     }
  }

  let(:invalid_attributes) {
    {name: "nt001",
     company_name: "カンパニー",
     bpuse_flg: "1",
     user_email: "",
     user_name: "USER",
     password: "pass1234",
     password_confirmation: "pass1234"
     }
  }

  let(:update_valid_attributes) {
    {name: "nt001",
     company_name: "カンパニー",
     bpuse_flg: "1"}
  }

  let(:update_invalid_attributes){
    {name: "nt001",
     company_name: "a" * 256,
     bpuse_flg: "1"}
  }

  it { should use_before_action(:authenticate_user!) }

  let(:tenant_setting_valid_params){
    {
      "file_size" => {setting_value: "600"},
      "licence_count" => {setting_value: "500"},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "use_authority" => {setting_value: "1"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }

  let(:tenant_setting_valid_params_2){
    {
      "file_size" => {setting_value: "600"},
      "contract_type" => {setting_value: "1"},
      "theme_color" => {setting_value: "orange"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }


  let(:tenant_setting_invalid_params){
    {
      "file_size" => {setting_value: ""},
      "licence_count" => {setting_value: "500"},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "use_authority" => {setting_value: "0"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }

  let(:tenant_setting_invalid_params_2){
    {
      "file_size" => {setting_value: "600"},
      "licence_count" => {setting_value: "#{Mynumber.key_1_search(nil).count - 1}"},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }

  let(:tenant_setting_invalid_params_3){
    {
      "file_size" => {setting_value: "600"},
      "licence_count" => {setting_value: ""},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }

  let(:tenant_setting_invalid_params_4){
    {
      "file_size" => {setting_value: "600"},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "use_authority" => {setting_value: "0"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }

  let(:tenant_setting_invalid_params_5){
    {
      "file_size" => {setting_value: ""},
      "licence_count" => {setting_value: ""},
      "contract_type" => {setting_value: "0"},
      "theme_color" => {setting_value: "orange"},
      "mynumber_ban" => {setting_value: "0"}
    }
  }



  describe "schema public" do

    before(:each) do
      Apartment::Tenant.switch! 'public'
      SeedFu.seed(SeedFu.fixture_paths,/tenants/)
    end

    describe "login not auth user" do

      login_user

      describe "GET index" do
        it {
          get :index
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        }
      end

      describe "GET new" do
        it{
          get :new
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        }
      end

      describe "POST create" do
        it {
          post :create, params: {:tenant => valid_attributes,:tenant_setting => tenant_setting_valid_params}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        }

        it{
          expect {
            post :create, params: {:tenant => valid_attributes,:tenant_setting => tenant_setting_valid_params}
          }.to change(Tenant, :count).by(0)
        }

      end

      describe "GET edit" do
        it {
          get :edit,params:  {:id => 2}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        }
      end

      describe "PUT #update" do
        it do
          put :update, params: {:id => 2, :tenant => update_valid_attributes}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "DELETE #destroy" do
        it do
          expect {
            delete :destroy, params: {:id => 2}
          }.to change(Tenant, :count).by(0)
        end

        it do
          delete :destroy,params:  {:id => 2}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "PUT #change_status" do

        let(:record){ Tenant.find(2) }

        context "when stop_flg=true" do

          before{ record.update_attribute(:stop_flg, true) }

          it "stop_flg to false" do
            put :change_status,params: {:id=>2}
            record.reload
            expect(record.stop_flg).to be_truthy
            expect(record.updated_account_id).not_to eq(@login_user.id)
          end

          it "redirects to the tenants list" do
            put :change_status,params: {:id=>2}
            should render_template('errors/error_page')
            should set_flash.now[:error]
            should respond_with(403)
          end

        end

        context "when stop_flg=false" do

          before{ record.update_attribute(:stop_flg, false) }

          it "stop_flg to true" do
            put :change_status,params: {:id=>2}
            record.reload
            expect(record.stop_flg).to be_falsy
            expect(record.updated_account_id).not_to eq(@login_user.id)
          end

          it "redirects to the tenants list" do
            put :change_status,params: {:id=>2}
            should render_template('errors/error_page')
            should set_flash.now[:error]
            should respond_with(403)
          end


        end

      end


    end

    describe "login_super_admin" do

      login_super_admin

      # This should return the minimal set of attributes required to create a valid
      # Tenant. As you add validations to Tenant, be sure to
      # adjust the attributes here as well.


      # This should return the minimal set of values that should be in the session
      # in order to pass any filters (e.g. authentication) defined in
      # TenantsController. Be sure to keep this updated too.

      describe "GET #index" do
        it "assigns all tenants as @tenants" do
          get :index, {}
          expect(assigns(:tenants).size).to eq(2)
        end

        context "Paging" do

          before{
            Tenant.find(1).update(created_at: 2.days.ago)
            Tenant.find(2).update(created_at: 1.days.ago)
            @create_tenants = []
            10.times do |n|
              tenant = FactoryBot.create(:tenant,created_at: (n+1).hours.ago)
              @create_tenants.push tenant
            end
          }

          it "Page 1" do
            get :index
            expect(assigns(:tenants).size).to eq(10)
            expect(assigns(:tenants).first).to eq(@create_tenants.first)
            expect(assigns(:tenants).last).to eq(@create_tenants.last)
          end

          it "Page 2" do
            get :index, params: {page: 2}
            expect(assigns(:tenants).size).to eq(2)
            expect(assigns(:tenants).pluck(:name)).to eq(["other","sample"])
          end

        end

      end

      describe "GET #show" do
        it "assigns the requested tenant as @tenant" do
          get :show,params:  {:id => 1}
          expect(assigns(:tenant).name).to eq("sample")
          expect(assigns(:tenant_setting).size).to eq(TenantSetting::EDITABLE_KEYS.size)
        end

        describe "参照中のテナントの管理者ユーザーを取得し、詳細画面に表示" do

          before{
            Apartment::Tenant.switch("sample") do
              User.delete_all
              FactoryBot.create(:number_handler,name: "NM_USER")
              FactoryBot.create(:number_manager,name: "NM_MANAGER")
              FactoryBot.create(:admin,name: "ADMIN_USER")
              FactoryBot.create(:super_admin,name: "SUPERADMIN_USER")
            end
          }

          it "@tenant_usersにadmin、super_adminロールのユーザー取得" do
            get :show,params:  {:id => 1}
            expect(assigns(:tenant_users).size).to eq(2)
            expect(assigns(:tenant_users).collect{|r| r.name}).to match(["ADMIN_USER","SUPERADMIN_USER"])
          end

        end

        describe "テナント設定があるとき" do
          before{
            Apartment::Tenant.switch("sample") do
              TenantSetting.create(setting_key: :file_size,setting_value: 600)
              TenantSetting.create(setting_key: :licence_count,setting_value: 400)
              TenantSetting.create(setting_key: :contract_type,setting_value: 0)
              TenantSetting.create(setting_key: :theme_color,setting_value: "blue")
              TenantSetting.create(setting_key: :use_authority,setting_value: "1")
              TenantSetting.create(setting_key: :management_division,setting_value: "1")
              TenantSetting.create(setting_key: :mynumber_ban,setting_value: "0")
            end
          }

          it{
            get :show, params: {:id => 1}
            expect(
              assigns(:tenant_setting).map{|setting| [setting.setting_key,setting.setting_value] }
            ).to match([
              ["file_size","600"],["contract_type","0"],
              ["licence_count","400"],["theme_color","blue"],
              ["use_authority","1"],["mynumber_ban","0"]
            ]
            )
          }

        end


      end

      describe "GET #new" do
        it "assigns a new tenant as @tenant" do
          get :new, {}
          expect(assigns(:tenant)).to be_a_new(Tenant)
          expect(assigns(:tenant_setting).collect{|r| r.setting_key }).to match(TenantSetting::EDITABLE_KEYS)
        end
      end

      describe "GET #edit" do
        it "assigns the requested tenant as @tenant" do
          get :edit, params: {:id => 1}
          expect(assigns(:tenant).name).to eq("sample")
        end

        it "テナント設定の取得" do
          get :edit, params: {:id => 1}
          expect(assigns(:tenant_setting).size).to eq(TenantSetting::EDITABLE_KEYS.size)
        end

        describe "テナント設定があるとき" do
          before{
            Apartment::Tenant.switch("sample") do
              TenantSetting.create(setting_key: :file_size,setting_value: 600)
              TenantSetting.create(setting_key: :licence_count,setting_value: 400)
              TenantSetting.create(setting_key: :contract_type,setting_value: 0)
              TenantSetting.create(setting_key: :theme_color,setting_value: "blue")
              TenantSetting.create(setting_key: :use_authority,setting_value: "0")
              TenantSetting.create(setting_key: :mynumber_ban,setting_value: "0")
            end
          }

          it{
            get :edit, params: {:id => 1}
            expect(
              assigns(:tenant_setting).map{|setting| [setting.setting_key,setting.setting_value] }
            ).to match([
              ["file_size","600"],["contract_type","0"],
              ["licence_count","400"],["theme_color","blue"],
              ["use_authority","0"],["mynumber_ban","0"]
            ]
            )
          }

          describe "設定保存済みでマイナンバー情報で管理番号が2種類以上になっているとき" do
            before{
              Apartment::Tenant.switch("sample") do
                FactoryBot.create(:mynumber_test_employee,key_2: "70000",manage_number: 0)
                FactoryBot.create(:mynumber_test_employee,key_2: "70000",manage_number: 1)
              end
            }
            it{
              get :edit, params: {:id => 1}
              expect(
                assigns(:tenant_setting).map{|setting| [setting.setting_key,setting.setting_value] }
              ).to match([
                ["file_size","600"],["contract_type","0"],
                ["licence_count","400"],["theme_color","blue"],
                ["mynumber_ban","0"]
              ]
              )
            }

          end

        end

      end

      describe "POST #create" do

        context "with valid params" do
          it "creates a new Tenant" do
            expect {
              post :create,
              params: {
                :tenant => valid_attributes,
                :tenant_setting => tenant_setting_valid_params
              }
            }.to change(Tenant, :count).by(1)
          end

          it "creates a new Tenant job" do

            Sidekiq::Testing.inline! do

              post :create, params: {:tenant => valid_attributes,:tenant_setting => tenant_setting_valid_params}
              should set_flash[:notice].to(I18n.t("messages.tenant.create_success"))
              expect(Apartment.tenant_names).to include(valid_attributes[:name])
              Apartment::Tenant.switch(valid_attributes[:name]) do
                expect(Checkway.count).to eq(4)
                expect(NumbercationMedium.count).to eq(3)
                expect(IdentificationMedium.count).to eq(5)
                expect(ColumnNameSetting.count).to eq(3)
                expect(User.count).to eq(1)
                user = User.first
                expect(user.email).to eq(valid_attributes[:user_email])

                expect(TenantSetting.file_size).to eq(600)
                expect(TenantSetting.licence_count).to eq("500")
                expect(TenantSetting.contract_type).to eq(false)
                expect(TenantSetting.theme_color).to eq("orange")

              end

              tenant = Tenant.last
              expect(tenant.name).to eq(valid_attributes[:name])
              expect(tenant.company_name).to eq(valid_attributes[:company_name])
              expect(tenant.created_account_id).to eq(@login_user.id)
              expect(tenant.updated_account_id).to eq(@login_user.id)
              expect(tenant.bpuse_flg).to be_truthy

            end

          end

          it("bpuse_flg は画面からの入力を受け付けない") do
            post :create, params: {:tenant => valid_attributes.merge({bpuse_flg: "0"}),
                                :tenant_setting => tenant_setting_valid_params}
            tenant = Tenant.last
            expect(tenant.bpuse_flg).to be_truthy
          end

        end

        context "with invalid params re-renders the 'new' template" do

          it "テナントのパラメータが不正" do
            post :create, params: {:tenant => invalid_attributes,
                :tenant_setting => tenant_setting_valid_params
              }
            expect(assigns(:tenant)).to be_a_new(Tenant)
            expect(response).to render_template("new")
          end

          it "テナント設定のパラメータが不正" do
            post :create,params:  {:tenant => valid_attributes,
                :tenant_setting => tenant_setting_invalid_params
              }
            expect(assigns(:tenant)).to be_a_new(Tenant)
            expect(response).to render_template("new")
          end

          it "固定制なのに、ライセンス数未入力" do
            post :create, params: {:tenant => invalid_attributes,
                :tenant_setting => tenant_setting_invalid_params_3
              }
            expect(assigns(:tenant)).to be_a_new(Tenant)
            expect(response).to render_template("new")
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present
          end

          it "固定制なのに、ライセンス数未送信" do
            post :create,params:  {:tenant => invalid_attributes,
                :tenant_setting => tenant_setting_invalid_params_4
              }
            expect(assigns(:tenant)).to be_a_new(Tenant)
            expect(response).to render_template("new")
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present
            expect(assigns(:tenant_setting).collect{|r| r.setting_key }).to match_array(TenantSetting::EDITABLE_KEYS)
          end

          it "確認資料ファイル制限サイズ未入力かつ、固定制なのに、ライセンス数未送信" do
            post :create, params: {:tenant => invalid_attributes,
                :tenant_setting => tenant_setting_invalid_params_5
              }
            expect(assigns(:tenant)).to be_a_new(Tenant)
            expect(response).to render_template("new")
            expect(assigns(:tenant_setting).select{|r| r.file_size? && r.errors[:setting_value].present? }).to be_present
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present

          end


        end
      end

      describe "PUT #update" do
        context "with valid params" do

          it "updates the requested tenant" do
            put :update, params: {:id => 2,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_valid_params}
            tenant = Tenant.find(2)
            expect(tenant.name).to eq("other")
            expect(tenant.company_name).to eq(update_valid_attributes[:company_name])
            expect(tenant.updated_account_id).to eq(@login_user.id)
          end

          it("bpuse_flg は画面からの入力を受け付けない") do
            put :update,params:  {:id => 1,
              :tenant => update_valid_attributes.merge({bpuse_flg: "0"}),
              :tenant_setting => tenant_setting_valid_params
            }
            tenant = Tenant.find(1)
            expect(tenant.name).to eq("sample")
            expect(tenant.bpuse_flg).to be_truthy
          end

          it "redirects to the tenant" do
            put :update, params: {:id => 2,
              :tenant => update_valid_attributes,
              :tenant_setting => tenant_setting_valid_params}
            should set_flash[:notice].to(I18n.t("messages.tenant.update_success"))
            expect(response).to redirect_to(tenant_path(2))
          end

          it "テナント設定が更新されること" do
            put :update,params:  {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_valid_params}

            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(6)
              expect(TenantSetting.file_size).to eq(600)
              expect(TenantSetting.licence_count).to eq("500")
              expect(TenantSetting.contract_type).to eq(false)
              expect(TenantSetting.theme_color).to eq("orange")
            end


          end

          describe "テナント設定が更新されること" do
            before{
              Apartment::Tenant.switch("sample") do
                TenantSetting.create(setting_key: :licence_count,setting_value: 500)
              end
            }
            it{
              put :update, params: {:id => 1,
                  :tenant => update_valid_attributes,
                  :tenant_setting => tenant_setting_valid_params_2}

              Apartment::Tenant.switch("sample") do
                expect(TenantSetting.count).to eq(5)
                expect(TenantSetting.file_size).to eq(600)
                expect(TenantSetting.licence_count).to eq("500")
                expect(TenantSetting.contract_type).to eq(true)
                expect(TenantSetting.theme_color).to eq("orange")
                expect(TenantSetting.mynumber_ban).to eq(false)
              end
            }


          end


        end

        context "with invalid params" do
          it "assigns the tenant as @tenant" do
            put :update, params: {:id => 1, :tenant => update_invalid_attributes,
                :tenant_setting => tenant_setting_valid_params}
            expect(assigns(:tenant).company_name).to eq("a" * 256)
          end

          it "re-renders the 'edit' template" do
            put :update,params: {:id => 1, :tenant => update_invalid_attributes,
                :tenant_setting => tenant_setting_valid_params}
            expect(response).to render_template("edit")
          end

          it "テナント設定が更新されないこと" do
            put :update, params: {:id => 1, :tenant => update_invalid_attributes,
                :tenant_setting => tenant_setting_valid_params}

            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end

          end

        end

        context "with invalid テナント設定 params" do

          it("テナントが更新されないこと"){
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params}
            tenant = Tenant.find(1)
            expect(tenant.name).to eq("sample")
            expect(tenant.company_name).not_to eq(update_valid_attributes[:company_name])
            expect(tenant.updated_account_id).not_to eq(@login_user.id)
          }

          it "テナント設定が更新されないこと" do
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params}

            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end

          end

          it "テナント設定が更新されないこと" do
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params_2}

            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end

          end

          it "固定制なのに、ライセンス数未入力" do
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params_3}
            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present
          end

          it "固定制なのに、ライセンス数未送信" do
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params_4}
            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present
            expect(assigns(:tenant_setting).collect{|r| r.setting_key }).to match_array(TenantSetting::EDITABLE_KEYS)
          end

          it "確認資料ファイル制限サイズ未入力かつ、固定制なのに、ライセンス数未送信" do
            put :update, params: {:id => 1,
                :tenant => update_valid_attributes,
                :tenant_setting => tenant_setting_invalid_params_5}
            Apartment::Tenant.switch("sample") do
              expect(TenantSetting.count).to eq(0)
              expect(TenantSetting.file_size).to eq(300)
              expect(TenantSetting.licence_count).to be_blank
              expect(TenantSetting.contract_type).to eq(true)
              expect(TenantSetting.theme_color).to eq("green")
            end
            expect(assigns(:tenant_setting).select{|r| r.file_size? && r.errors[:setting_value].present? }).to be_present
            expect(assigns(:tenant_setting).select{|r| r.licence_count? && r.errors[:setting_value].present? }).to be_present

          end



        end



      end

      describe "DELETE #destroy" do
        it "destroys the requested tenant" do
          expect {
            delete :destroy, params: {:id => 2}
          }.to change(Tenant, :count).by(-1)
        end

        it "redirects to the tenants list" do
          delete :destroy,params:  {:id => 2}
          should set_flash[:notice].to(I18n.t("messages.tenant.destroy_success"))
          expect(response).to redirect_to(tenants_url)
        end
      end

      describe "PUT #change_status" do

        let(:record){ Tenant.find(2) }

        context "when stop_flg=true" do

          before{ record.update_attribute(:stop_flg, true) }

          it "stop_flg to false" do
            put :change_status,params: {:id=>2}
            record.reload
            expect(record.stop_flg).to be_falsy
            expect(record.updated_account_id).to eq(@login_user.id)
          end

          it "redirects to the tenants list" do
            put :change_status,params: {:id=>2}
            should set_flash[:notice].to(I18n.t("messages.tenant.change_status.restart"))
            expect(response).to redirect_to(tenants_url)
          end

        end

        context "when stop_flg=false" do

          before{ record.update_attribute(:stop_flg, false) }

          it "stop_flg to true" do
            put :change_status,params: {:id=>2}
            record.reload
            expect(record.stop_flg).to be_truthy
            expect(record.updated_account_id).to eq(@login_user.id)
          end

          it "redirects to the tenants list" do
            put :change_status,params: {:id=>2}
            should set_flash[:notice].to(I18n.t("messages.tenant.change_status.stop"))
            expect(response).to redirect_to(tenants_url)

          end


        end

      end

      describe "テナントのユーザーに対する操作" do

        describe "アカウント未承認のユーザー" do
          before{
            ActionMailer::Base.deliveries.clear
            Apartment::Tenant.switch("sample") do
              @user = FactoryBot.create(:admin,name: "ADMIN_USER",confirmed_at: nil)
              @user_id = @user.id
              @user_email = @user.email
            end
          }

          # テナントの指定ユーザーに案内メール再送信
          it "POST email_resend" do
            post :email_resend,params: {id: 1,user_id: @user_id}
            expect(assigns(:tenant).name).to eq("sample")
            token = ""

            Apartment::Tenant.switch("sample") do
              @user.reload
              expect(@user.confirmed_at).to be_blank
              expect(@user.confirmation_token).to be_present
              expect(@user.confirmation_sent_at).to be_present
              expect(@user.reset_password_sent_at).to be_blank
              expect(@user.reset_password_token).to be_blank
              token = @user.confirmation_token
            end

            email = ActionMailer::Base.deliveries.last
            expect(email.to[0]).to eq(@user_email)
            expect(email.body.encoded).to match(/\/sample\/users\/confirmation\?confirmation_token=([^"]+)/)
            expect(token).to eq(
                email.body.encoded.match(/\/sample\/users\/confirmation\?confirmation_token=([^"]+)/)[1]
            )

            should set_flash[:notice].to(I18n.t("messages.tenant.info_email_resend.success",email: @user_email))
            expect(response).to redirect_to(tenant_path(1))

          end

          # テナントの指定ユーザーのEメールアドレスを変更フォーム表示
          it "GET email_edit.js" do

            get :email_edit,params: {id: 1,user_id: @user_id},xhr: true
            expect(assigns(:user_id)).to eq(@user_id)
            expect(assigns(:user_email)).to eq(@user_email)
            expect(response).to render_template("email_edit")


          end

          # テナントの指定ユーザーのEメールアドレスを変更して案内メール再送信
          describe "PUT email_update.js" do

            let(:new_email){ "new_resend_address@mail.com" }
            before{
              ActionMailer::Base.deliveries.clear
            }

            it "正常" do
              post :email_update,params: {id: 1,user_id: @user_id,user: {email: new_email}},xhr: true
              expect(response).to render_template("email_update")

              token = ""

              Apartment::Tenant.switch("sample") do
                @user.reload
                expect(@user.confirmed_at).to be_blank
                expect(@user.confirmation_token).to be_present
                expect(@user.confirmation_sent_at).to be_present
                expect(@user.reset_password_sent_at).to be_blank
                expect(@user.reset_password_token).to be_blank
                token = @user.confirmation_token
              end

              email = ActionMailer::Base.deliveries.last
              expect(email.to[0]).to eq(new_email)
              expect(email.body.encoded).to match(/\/sample\/users\/confirmation\?confirmation_token=([^"]+)/)
              expect(token).to eq(
                email.body.encoded.match(/\/sample\/users\/confirmation\?confirmation_token=([^"]+)/)[1]
              )



            end

            it "Eメール空白" do

              post :email_update,params: {id: 1,user_id: @user_id,user: {email: ""}},xhr: true

              expect(ActionMailer::Base.deliveries.last).to be_blank

              Apartment::Tenant.switch("sample") do
                @user.reload
                expect(@user.confirmed_at).to be_blank
              end

              expect(assigns(:tenant_user).errors[:email]).to be_present
              expect(response).to render_template("email_edit")

            end

            describe "Eメール重複" do
              before{
                Apartment::Tenant.switch("sample") do
                  FactoryBot.create(:admin,name: "ADMIN_USER_2",email: new_email)
                end
              }

              it do

                post :email_update,params: {id: 1,user_id: @user_id,user: {email: new_email}},xhr: true

                expect(ActionMailer::Base.deliveries.last).to be_blank

                Apartment::Tenant.switch("sample") do
                  @user.reload
                  expect(@user.confirmed_at).to be_blank
                end

                expect(assigns(:tenant_user).errors[:email]).to be_present
                expect(ActionMailer::Base.deliveries.last).to be_blank

              end

            end

          end

        end

        describe "アカウント承認済みのユーザー" do

          before{
            ActionMailer::Base.deliveries.clear
            Apartment::Tenant.switch("sample") do
              @user = FactoryBot.create(:admin,name: "ADMIN_USER")
              @user_id = @user.id
              @user_email = @user.email
            end
          }


          # テナントの指定ユーザーにパスワード再設定メール送信
          it "POST email_resend" do
            post :email_resend,params: {id: 1,user_id: @user_id}
            expect(assigns(:tenant).name).to eq("sample")
            token = ""

            Apartment::Tenant.switch("sample") do
              @user.reload
              expect(@user.reset_password_sent_at).to be_present
              expect(@user.reset_password_token).to be_present
              token = @user.reset_password_token
            end

            email = ActionMailer::Base.deliveries.last
            expect(email.to[0]).to eq(@user_email)
            expect(email.body.encoded).to match(/\/sample\/users\/password\/edit\?reset_password_token=([^"]+)/)
            expect(token).to eq(
              Devise.token_generator.digest(User, :reset_password_token,
                email.body.encoded.match(/\/sample\/users\/password\/edit\?reset_password_token=([^"]+)/)[1])
            )

            should set_flash[:notice].to(I18n.t("messages.tenant.email_resend.success",email: @user_email))
            expect(response).to redirect_to(tenant_path(1))

          end

          # テナントの指定ユーザーのEメールアドレスを変更フォーム表示
          it "GET email_edit.js" do

            get :email_edit,params: {id: 1,user_id: @user_id},xhr: true
            expect(assigns(:user_id)).to eq(@user_id)
            expect(assigns(:user_email)).to eq(@user_email)
            expect(response).to render_template("email_edit")


          end

          # テナントの指定ユーザーのEメールアドレスを変更してパスワード再設定メール送信
          describe "PUT email_update.js" do

            let(:new_email){ "new_resend_address@mail.com" }
            before{
              ActionMailer::Base.deliveries.clear
            }

            it "正常" do
              post :email_update,params: {id: 1,user_id: @user_id,user: {email: new_email}},xhr: true
              expect(response).to render_template("email_update")

              token = ""

              Apartment::Tenant.switch("sample") do
                @user.reload
                expect(@user.email).to eq(new_email)
                expect(@user.reset_password_sent_at).to be_present
                expect(@user.reset_password_token).to be_present
                token = @user.reset_password_token
              end

              email = ActionMailer::Base.deliveries.last
              expect(email.to[0]).to eq(new_email)
              expect(email.body.encoded).to match(/\/sample\/users\/password\/edit\?reset_password_token=([^"]+)/)
              expect(token).to eq(
                Devise.token_generator.digest(User, :reset_password_token,
                  email.body.encoded.match(/\/sample\/users\/password\/edit\?reset_password_token=([^"]+)/)[1])
              )



            end

            it "Eメール空白" do

              post :email_update,params: {id: 1,user_id: @user_id,user: {email: ""}},xhr: true

              expect(ActionMailer::Base.deliveries.last).to be_blank

              Apartment::Tenant.switch("sample") do
                @user.reload
                expect(@user.reset_password_sent_at).to be_blank
                expect(@user.reset_password_token).to be_blank
              end

              expect(assigns(:tenant_user).errors[:email]).to be_present
              expect(response).to render_template("email_edit")

            end

            describe "Eメール重複" do
              before{
                Apartment::Tenant.switch("sample") do
                  FactoryBot.create(:admin,name: "ADMIN_USER_2",email: new_email)
                end
              }

              it do

                post :email_update,params: {id: 1,user_id: @user_id,user: {email: new_email}},xhr: true

                expect(ActionMailer::Base.deliveries.last).to be_blank

                Apartment::Tenant.switch("sample") do
                  @user.reload
                  expect(@user.reset_password_sent_at).to be_blank
                  expect(@user.reset_password_token).to be_blank
                end

                expect(assigns(:tenant_user).errors[:email]).to be_present
                expect(ActionMailer::Base.deliveries.last).to be_blank

              end

            end

          end

        end #アカウント承認済みのユーザー

      end #テナントのユーザーに対する操作


    end

  end

  describe "schema not public" do
    before(:each) do
      Apartment::Tenant.switch! 'sample'
    end

    describe "login_super_admin" do

      login_super_admin

      describe "GET #index" do
        it do
          get :index
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "GET #show" do
        it do
          get :show,params:  {:id => 1}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "GET #new" do
        it do
          get :new
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "GET #edit" do
        it do
          get :edit,params:  {:id => 1}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end
      end

      describe "POST #create" do

        context "with valid params" do
          it "not creates a new Tenant" do
            expect {
              post :create, params: {:tenant => valid_attributes}
            }.to change(Tenant, :count).by(0)
          end

          it "assigns a newly created tenant as @tenant" do
            post :create, params: {:tenant => valid_attributes}
            should render_template('errors/error_page')
            should set_flash.now[:error]
            should respond_with(403)
          end
        end

      end

      describe "PUT #update" do

        context "with valid params" do

          it do
            put :update, params: {:id => 2, :tenant => update_valid_attributes}
            should render_template('errors/error_page')
            should set_flash.now[:error]
            should respond_with(403)
          end

        end

      end

      describe "PUT #change_status" do

        it do
          put :change_status,params:  {:id => 2, :tenant => update_valid_attributes}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end

      end

      describe "DELETE #destroy" do
        it "destroys the requested tenant" do
          delete :destroy,params:  {:id => 2}
          should render_template('errors/error_page')
          should set_flash.now[:error]
          should respond_with(403)
        end

      end

    end

  end



end