【问题标题】:testing devise and cancan in controller specs (rspec)在控制器规范 (rspec) 中测试设计和 cancan
【发布时间】:2011-05-12 04:34:43
【问题描述】:

现在我的 CanCan 和 Devise 运行良好,我需要添加到我的测试中。

我是否应该期望得到双倍的测试数量,甚至更多?我需要以“访客”用户身份测试所有内容,然后以用户身份和管理员身份测试。

如果使用 rspec,您将如何布局?

describe "GET edit" do
    login_admin
    it "assigns the requested forum_topic as @forum_topic" do
      ForumTopic.stub(:find).with("37") { mock_forum_topic }
      get :edit, :id => "37"
      response.should redirect_to( new_user_session_path )
    end

    it "assigns the requested forum_topic as @forum_topic" do
      ForumTopic.stub(:find).with("37") { mock_forum_topic }
      get :edit, :id => "37"
      assigns(:forum_topic).should be(mock_forum_topic)
    end
end

帮助模块

  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in Factory.create(:admin)
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @user = Factory.create(:user)
      sign_in @user
    end
  end

【问题讨论】:

    标签: ruby-on-rails rspec devise functional-testing cancan


    【解决方案1】:

    测试CanCan时通常做的是测试能力文件本身。

    例如,如果您在您的应用程序中进行测试,除非已签名,否则您应该无法查看某个论坛,您可以像这样进行测试:

    @user = Factory.create(:user)
    @forum = Factory.create(:forum)
    
    describe "User ability" do
      it "Should be able to view forums" do
        @ability = Ability.new(@user)
        @ability.should be_able_to(:show, @forum)
      end
    end
    
    describe "nil ability" do
      it "Should be not be able to view forums if not signed in" do
        @ability = Ability.new(nil)
        @ability.should_not be_able_to(:show, @forum)
      end
    end
    

    这只是一个例子。

    你可以阅读更多关于它的信息:https://github.com/ryanb/cancan/wiki/Testing-Abilities

    最后为了测试设计,我只使用 capybara 进行集成测试,并使用管理员和用户登录。

    【讨论】:

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