且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails、Restful 身份验证和RSpec - 如何测试需要身份验证的新模型

更新时间:2023-12-04 21:11:34

我有一个非常相似的设置,下面是我目前用来测试这些东西的代码.在我输入的每个 describe 中:

I have a very similar setup, and below is the code I'm currently using to test this stuff. In each of the describes I put in:

it_should_behave_like "login-required object"
def attempt_access; do_post; end

如果您只需要登录,或者

If all you need is a login, or

it_should_behave_like "ownership-required object"
def login_as_object_owner; login_as @product.user; end
def attempt_access; do_put; end
def successful_ownership_access
  response.should redirect_to(product_url(@product))
end

如果您需要所有权.显然,辅助方法每轮都会改变(很少),但这为您完成了大部分工作.这是在我的 spec_helper.rb 中

If you need ownership. Obviously, the helper methods change (very little) with each turn, but this does most of the work for you. This is in my spec_helper.rb

shared_examples_for "login-required object" do
  it "should not be able to access this without logging in" do
    attempt_access

    response.should_not be_success
    respond_to do |format|
      format.html { redirect_to(login_url) }
      format.xml { response.status_code.should == 401 }
    end
  end
end

shared_examples_for "ownership-required object" do
  it_should_behave_like "login-required object"

  it "should not be able to access this without owning it" do
    attempt_access

    response.should_not be_success
    respond_to do |format|
      format.html { response.should be_redirect }
      format.xml { response.status_code.should == 401 }
    end
  end

  it "should be able to access this if you own it" do
    login_as_object_owner
    attempt_access

    if respond_to?(:successful_ownership_access)
      successful_ownership_access
    else
      response.should be_success
    end
  end
end