2012-04-10 96 views
1
有麻煩

我會針對與由慘慘控制的鏈接的存在測試:測試慘慘的看法使用RSpec

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 %> 

當我運行測試,它會失敗,併產生此錯誤:

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

expected link "New article" to return something 

這很奇怪,因爲它工作時,我手動測試它在米y瀏覽器。這裏的能力類:

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 

我有一種預感,它是與我是如何定義的能力一流,但我找不到我哪裏錯了。任何幫助都感激不盡。謝謝:)

+1

CanCan是否真的允許你做'可以嗎? :創建,@文章'?我假設'@ articles'是這裏的一組文章。它不應該像'可以嗎? :創造,:文章或'可以嗎? :創造,文章? 另外,你真的可以在規範中有這麼多的嵌套函數調用嗎?爲了清楚說明,你是否嘗試過使用'it {should have_link('New article',:href => new_article_path)}'? – Frost 2012-04-10 11:55:35

+0

@Frost,把它改成'可以嗎? :創造,文章'工作。這很奇怪,因爲我只是遵循RailsCasts插曲,所以我確信它會起作用。無論如何,您應該將其作爲答案發布,以便我可以接受。謝謝:) – 2012-04-10 12:17:17

+0

完成:http://stackoverflow.com/questions/10086150/having-trouble-testing-cancan-views-with-rspec/10089429#10089429 – Frost 2012-04-10 13:09:28

回答

0

在視圖中,在那裏你做

if can? :create, @articles 

我猜你傳遞一個數組can?,這似乎有點奇怪。

據我所知,can?方法需要符號或類。

嘗試用Article:articles替換@articles