在控制器规范(RSpec)中测试Devise和CanCan

3
现在我已经成功地使用了CanCan和Devise,我需要添加测试。我应该期望测试的数量翻倍甚至更多吗?我需要测试每个角色,包括“guest”用户、普通用户和管理员。
对于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
1个回答

2

在测试 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上了解更多相关信息。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接