无法使用RSpec测试CanCan视图

时间:2012-04-10 09:26:55

标签: ruby-on-rails rspec capybara cancan fabrication-gem

我正在测试是否存在由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 =&gt; 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和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

我有一种预感,它与我如何定义能力等级有关,但我无法找到我出错的地方。任何帮助都感激不尽。谢谢:))

1 个答案:

答案 0 :(得分:0)

在视图中,您执行的操作

if can? :create, @articles

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

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

尝试将@articles替换为Article:articles