简体   繁体   中英

Rails rspec test for controller cancan abilities

I would like to write a test to make sure that "expert" users can create articles, and "basic" users cannot. For example, basic user cannot go here: "http://0.0.0.0:3000/articles/new" . Below is a shortened version of my articles controller, followed by the articles test. The controller works, but I would like the test to prove it out. I'm not sure what to put where it says "code goes here". Thanks.

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

Testing CanCan abilities from your Controllers' specs will blow up your specs soon.

I prefer to test abilities in spec/models/ability_spec.rb using cancan/matchers

in your spec file, you can do it like:

describe "create article" do
  it "should not create new article" do
    get :new
    expect(response).not_to render_template("new")
  end
end

In document of cancan , see https://github.com/ryanb/cancan/wiki/Testing-Abilities , you can get details.

Instead of testing what shouldn't happen, consider the simpler test of what should happen:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM