开发者

testing devise and cancan in controller specs (rspec)

开发者 https://www.devze.com 2023-03-05 19:45 出处:网络
Now that I have CanCan and Devise working nicely I need to add to my tests. Should I expect to end up with double the number of tests, maybe more?I need to test everything as a\"guest\" user then tes

Now that I have CanCan and Devise working nicely I need to add to my tests.

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?

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(:ad开发者_开发知识库min)
    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.

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

And finally to test devise I just do integration testing with capybara, and sign in with admin and user.

0

精彩评论

暂无评论...
验证码 换一张
取 消