Rails rspec test for controller cancan abilities

試著忘記壹切 提交于 2019-12-13 07:36:54

问题


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

回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/18326983/rails-rspec-test-for-controller-cancan-abilities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!