【问题标题】:Rails rspec test for controller cancan abilities控制器 cancan 能力的 Rails rspec 测试
【发布时间】:2013-08-20 04:30:42
【问题描述】:

我想编写一个测试以确保“专家”用户可以创建文章,而“基本”用户不能。例如,基本用户不能去这里:"http://0.0.0.0:3000/articles/new"。下面是我的文章控制器的缩短版本,然后是文章测试。控制器可以工作,但我希望通过测试来证明这一点。我不知道在上面写着“代码在这里”的地方放什么。谢谢。

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

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    根据控制器的规格测试 CanCan 能力很快就会破坏您的规格。

    我更喜欢使用cancan/matchers 来测试spec/models/ability_spec.rb 中的能力

    【讨论】:

    • 我实际上是在尝试决定是在模型还是控制器规格中测试我的能力。您能解释一下为什么您认为我在模型规范中进行测试是首选方式吗?
    • 它更快,需要更少的代码来覆盖大多数情况,所有测试都在同一个地方。
    • 在我的第 10 个规范尝试从控制器解析 json 之后,我想我开始同意了。只测试能力比根据能力测试整个控制器要容易得多。
    【解决方案2】:

    在您的规范文件中,您可以这样做:

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

    在cancan的文档中,见https://github.com/ryanb/cancan/wiki/Testing-Abilities,可以了解详情。

    【讨论】:

      【解决方案3】:

      与其测试不应该发生什么,不如考虑更简单的测试应该发生什么:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        相关资源
        最近更新 更多