首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby教程Ch9练习#9 -测试失败

Ruby教程Ch9练习#9 -测试失败
EN

Stack Overflow用户
提问于 2012-11-01 23:52:13
回答 1查看 142关注 0票数 0

我试着搜索这个,发现了许多问题,没有一个能给我一个有效的答案。我应该做一个测试,以确保管理员用户不能删除自己。

下面是我在authentication_pages_spec.rb中拥有的内容

代码语言:javascript
复制
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中拥有的内容

代码语言:javascript
复制
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

测试失败,返回结果:

代码语言:javascript
复制
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 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-02 13:42:21

这就是我所做的。希望它至少可以作为参考。

spec/requests/authentication_pages.spec

代码语言:javascript
复制
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

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13180713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档