2013-08-20 205 views
0

我想寫一個測試以確保「專家」用戶可以創建文章,而「基本」用戶不能。例如,基本用戶不能去這裏:"http://0.0.0.0:3000/articles/new"。以下是我的文章控制器的縮寫版本,後面是文章測試。控制器工作,但我希望測試證明它。我不知道該在什麼地方說「代碼在這裏」。謝謝。Rails rspec測試控制器cancan功能

articles_controller:

class ArticlesController < ApplicationController 
    load_and_authorize_resource 

     # GET /articles/new 
     # GET /articles/new.json 
     def new 
     puts "in articles new" 
     @article = Article.new 

     respond_to do |format| 
      format.html # new.html.erb 
      format.json { render json: @article } 
     end 
     end 
    end 

articles_controller_spec:

describe ArticlesController do 

    before (:each) do 
    @user = FactoryGirl.create(:user) 
    @user.role = "basic" 
    sign_in @user 
    end 

    describe "create article" do 
    it "should not create new article" do 
     #code goes here 
    end 
    end 
end 

回答

2

根據您的控制器規格測試CanCan能力會很快炸燬您的規格。

我更喜歡使用cancan/matchers

+0

我其實是想決定是否在模型或控制器規格中測試我的能力。你能解釋爲什麼你認爲我在模型規範中測試是首選方法嗎? – Emeka

+1

速度更快,需要更少的代碼才能覆蓋大部分情況,並且所有測試都在同一個地方。 – ck3g

+0

在我的第10個規範試圖從控制器中解析json之後,我想我開始同意了。根據能力,測試比整個控制器的能力要容易得多。 – Emeka

0

不檢測什麼不應發生在spec/models/ability_spec.rb測試能力,考慮什麼應該發生了簡單的測試:

it "should return 401" do 
    get :new 
    expect(response.status).to eq(401) 
end