0

これを検索してみたところ、多くの質問が見つかりましたが、どれもうまくいく答えを得ることができませんでした. 管理者ユーザーが自分自身を削除できないことを確認するためのテストを行うことになっています。

これが authentication_pages_spec.rb にあるものです

describe "as admin user" do
  let(:admin) { FactoryGirl.create(:admin) }
  before { sign_in admin }

  describe "can't delete self" do
    before { delete user_path(admin) }
    specify { response.should redirect_to(users_path), 
              flash[:error].should =~ /Cannot delete own admin account!/i }
  end      
end

これがusers_controller.rbにあるものです

def destroy
    user = User.find(params[:id])
    if (current_user == user) && (current_user.admin?)
      flash[:error] = "Cannot delete own admin account!"
    else
      user.destroy
      flash[:success] = "User destroyed."
    end
  redirect_to users_path
end

テストは次の結果で失敗します:

1) Authentication authorization as admin user can't delete self 
     Failure/Error: flash[:error].should =~ /Cannot delete own admin account!/i }
       expected: /Cannot delete own admin account!/i
            got: nil (using =~)
     # ./spec/requests/authentication_pages_spec.rb:139:in `block (5 levels) in <top (required)>'

Finished in 3.75 seconds
83 examples, 1 failure

Failed examples:

rspec ./spec/requests/authentication_pages_spec.rb:138 # Authentication authorization as admin user can't delete self 
4

1 に答える 1

3

これが私がしたことです。少しでも参考になれば幸いです。

仕様/リクエスト/authentication_pages.spec

describe "authorization" do
  ...

  context "as an admin user" do
    let(:admin) { create(:admin) }

    before do
      visit signin_path
      sign_in(admin)
    end

    context "prevents admin users from destroying themselves" do
      it "does not delete the user" do
        expect do
          delete user_path(admin)
        end.not_to change(User, :count)
      end

      context "after failing to delete" do
        let(:no_suicide) { "Cannot delete own admin account!" }

        before { delete user_path(admin) }
        specify do
          response.should redirect_to(users_url),
                                      flash[:error].should == no_suicide
        end
      end
    end
  end
end

app/controllers/users_controller.rb

class UsersController < ApplicationController
  ...

  before_filter :admin_user, only: :destroy

  ...

  def destroy
    user = User.find(params[:id])
    if !current_user?(user)
      user.destroy
      flash[:success] = "User destroyed."
    else
      flash[:error] = "Cannot delete own admin account!"
    end
    redirect_to users_url
  end

  ...

  private

    def admin_user
      redirect_to root_url unless current_user.admin?
    end

    ...
end
于 2012-11-02T05:42:21.400 に答える