简体   繁体   English

在控制器规格(rspec)中测试设计和cancan

[英]testing devise and cancan in controller specs (rspec)

Now that I have CanCan and Devise working nicely I need to add to my tests. 现在我有CanCan和Devise很好地工作,我需要添加到我的测试中。

Should I expect to end up with double the number of tests, maybe more? 我应该期望最终测试次数增加一倍,或许更多吗? I need to test everything as a "guest" user then test as user and also as admin. 我需要将所有内容作为“访客”用户进行测试,然后作为用户和管理员进行测试。

With rspec how would you lay this out? 有了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

helper module 辅助模块

  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

What is usually done when testing CanCan, is testing the ability file per se. 测试CanCan时通常会做的是测试能力文件本身。

For example if you are testing that in your app you should not be able to view a certain forum unless signed you could test it out like so: 例如,如果你在你的应用程序中测试它,你应该无法查看某个论坛,除非签名你可以测试它如下:

@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

This is just an example. 这只是一个例子。

You can read more about it in: https://github.com/ryanb/cancan/wiki/Testing-Abilities 您可以在以下网址阅读更多相关信息: https//github.com/ryanb/cancan/wiki/Testing-Abilities

And finally to test devise I just do integration testing with capybara, and sign in with admin and user. 最后测试设计我只是与capybara进行集成测试,并使用admin和user登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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