登录用户的Rspec测试. [英] Rspec test for login user.CanCan

查看:52
本文介绍了登录用户的Rspec测试.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为能力等级创建rspec测试.我已经成功地编写了管理员功能并对其进行了测试,但是我不知道如何为登录用户编写测试(登录用户只能更新和销毁其自己的注释).

I am trying to create rspec test for ability class. I successfully wrote the ability for the admin and testing this, but I don't know how write the test for the login user(login user can only update and destroy its own comments).

这是capability.rb:

This is ability.rb:

    class Ability
      include CanCan::Ability

      def initialize(user)
        user ||= User.new
        if user.admin?
          can :manage, :all
        else
          can :read, :all
          can :create, :update, :destroy, Comment, user_id: user.id
        end
      end
    end

这是capability_spec.rb:

and this is ability_spec.rb:

    require 'rails_helper'
    require "cancan/matchers"

    describe Ability do
        it "user guest" do
            user = FactoryGirl.create(:user)
            ability = Ability.new(user)
            comment = Comment.new(user: user)
            expect(ability).to be_able_to(:read, comment)
        end

        it "user admin" do
            user = FactoryGirl.create(:user, role: 'admin')
            ability = Ability.new(user)
            comment = Comment.new(user: user)
            expect(ability).to be_able_to(:destroy, comment)
        end

推荐答案

将此代码添加到spec_helper RSpec.configure中.

Add this code in your spec_helper RSpec.configure.

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
  ...
end

这是在您的规格中使用devise助手.就像sign_in(user).因此,对于测试登录用户,您可以先对该用户签名像这样

This is to use devise helper in your specs. like sign_in(user). So, for testing logged in user you can first sign the user like this

it "user admin" do
    user = FactoryGirl.create(:user, role: 'admin')
    sign_in(user)
    # your code to test update and destroy ability
end    

这篇关于登录用户的Rspec测试.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆