1

我正在测试是否存在由 CanCan 控制的链接:

before do
  @author = Fabricate(:author)
  visit new_user_session_path
  fill_in 'Email', :with => @author.email
  fill_in 'Password', :with => @author.password
  click_button 'Sign in'
  visit articles_path
end

it { should have_link 'New article', :href => new_article_path }

这是它正在测试的视图:

<% if can? :create, @articles %>
  <%= link_to 'New article', new_article_path %>
<% end %>

当我运行测试时,它失败并产生此错误:

失败/错误:它 { should have_link 'New article', :href => new_article_path }

   expected link "New article" to return something

这很奇怪,因为当我在浏览器中手动测试它时它会起作用。下面是能力等级:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # Guest user

    if user.role? :admin
      can :manage, :all
    else
      can :read, :all

      if user.role?(:author)
        can :create, Article
        can :update, Article do |article|
          article.try(:author) == user
        end
        can :destroy, Article do |article|
          article.try(:author) == user
        end
      end
    end
  end
end

有关更多上下文,这是我的用户和 user_fabricator 类:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me
  attr_accessible :name, :roles

  has_many :articles, :foreign_key => 'author_id', :dependent => :destroy

  ROLES = %w[admin moderator author]

  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end

  def roles
    ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
  end

  def role?(role)
    roles.include?(role.to_s)
  end
end

用户角色方法基于 Ryan Bates 在他的 RailsCasts 剧集中的方法。这是制造商:

Fabricator(:user) do
  email { sequence(:email) { |i| "user#{i}@example.com" } }
  name { sequence(:name) { |i| "Example User-#{i}" } }
  password 'foobar'
end

Fabricator(:admin, :from => :user) do
  roles ['admin']
end

Fabricator(:author, :from => :user) do
  roles ['author']
end

我有一种预感,这与我如何定义能力等级有关,但我找不到哪里出错了。任何帮助都感激不尽。谢谢 :)

4

1 回答 1

0

在视图中,您在哪里

if can? :create, @articles

我猜你正在将一个数组传递给can?,这似乎有点奇怪。

据我所知,该can?方法需要一个符号或一个类。

尝试用@articlesorArticle替换:articles

于 2012-04-10T13:09:20.200 回答