简体   繁体   English

Rspec测试登录用户。

[英]Rspec test for login user.CanCan

I am trying to create rspec test for ability class. 我正在尝试为能力课程创建rspec测试。 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). 我已经成功地为管理员编写了该功能并对其进行了测试,但是我不知道如何为登录用户编写测试(登录用户只能更新和销毁其自己的注释)。

This is ability.rb: 这是capability.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

and this is ability_spec.rb: 这是capability_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

Add this code in your spec_helper RSpec.configure. 将此代码添加到您的spec_helper RSpec.configure中。

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

This is to use devise helper in your specs. 这是在您的规格中使用devise助手。 like sign_in(user). 像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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM