2

我是 rspec 测试的新手,也许有些东西我不明白。

如果可以帮助我,我真的很感激一些帮助。

文件结构:

app/models/booking.rb
app/models/user.rb
app/models/role.rb
app/models/ability.rb   

app/controllers/bookings_controller.rb

app/views/bookings/index.html.erb
app/views/dashboard/index.html.erb

app/spec/controllers/bookings_controller_spec.rb

我读了这个链接有一个类似的问题,但没有解决

Rspec 控制器错误,期望 <"index"> 但使用 <""> 呈现

是相似的,因为如果我改变这一行:

    it 'should not render index template from bookings' do
        get :index
=>      response.should_not render_template(:index)
    end

对于这个其他:

    it 'should not render index template from bookings' do
        get :index
=>      response.should render_template(:index)
    end

我在链接中遇到了同样的错误

期待 <"index"> 但使用 <""> 渲染

我不知道为什么?这是我的代码:

我的规格:

describe BookingsController do
context 'as guest' do
  before(:each) do
    @user = User.new(:email => 'mail_admin@test.com',
                :username => 'admin',
                :password => 'password_admin',
                :password_confirmation => 'password_admin')
    @user.save
    #when i save, with gem CanCan i assign a default role to @user
    #with the default role the user only can see the views/dashboard/index.html.erb
  end

  it 'should not render index template from bookings' do
    get :index
    response.should_not render_template(:index)
  end
end  
end

控制器:

class BookingsController < ApplicationController
load_and_authorize_resource

 def index
  ...      
 end

 def show
  ...
 end
end

我的模型:

class Booking < Activerecord::Base
paginates_per 20

 def 
  ...      
 end

 def 
  ...
 end
end

用户:

Class User < ActiveRecord::Base
  after_save :set_default_role
  rolify
  .
  .
  .
  .
  def set_default_role
   self.add_role :default
  end
end

角色:

class Role < ActiveRecord::Base
 ROLES = {"admin" => "Admin", "default" => "Default"}
 .
 .
 .
 . 
 scopify
end

能力:

class Ability
  include CanCan::Ability

  def initialize(user)
  user ||= User.new
  if user.has_role? :admin
   can :manage, :all
  elsif user.has_role? :data_consistency
   can :read, Booking
  end
 end
end
4

2 回答 2

1

CanCan 授权模型访问而不是控制器操作。对于大多数其他操作,这两者或多或少是同一件事,但对于索引则不同。在索引操作上,CanCan 将范围添加到包含您的授权限制的记录的查询中。

这意味着您的访客用户将根本无法看到任何记录,但视图仍将呈现。

您想要的是身份验证(即设计)并从需要经过身份验证的用户访问的每个控制器中的 before_filter 使用它。

class BookingsController < ApplicationController
  load_and_authorize_resource # Handles authorization
  before_filter !authenticate_user # Handles authentication (included with Devise)
  ...
end
于 2013-02-15T21:18:14.647 回答
0

就我而言,问题已在 before(:each) 块中解决!
我的代码是这样工作的:

before :each do
  @user = User.new(:email => 'mail_admin@test.com',
            :username => 'admin',
            :password => 'password_admin',
            :password_confirmation => 'password_admin')
  @user.confirm!
  sign_in @user
end  
于 2013-04-19T18:52:50.277 回答