我使用Bort创建了一个学习应用程序,这是一个包含Restful身份验证和RSpec的基础应用程序。我已经将其启动并运行,并添加了一个新对象,该对象要求用户在执行任何操作之前必须先登录(控制器中的before_filter :login_required)。编辑:我还应该提到新类的用户has_many,并且只有用户才能看到它。
我已经使用Rspec的生成器创建了新的模型/控制器,它已经创建了许多默认测试。一旦before_filter就位,如果没有before_filter但有几个失败了,它们都通过了,这是应该预料到的。
如何让生成的测试运行,就像有/没有登录的用户一样?我是否需要一整批匹配的未登录重定向测试?我假设它是某种模仿或固定技术,但我对RSpec还是个新手,有点糊涂。好的RSpec教程链接也将不胜感激。
发布于 2008-09-15 19:04:36
我有一个非常类似的设置,下面是我目前用来测试这个东西的代码。在我输入的每个describe中:
it_should_behave_like "login-required object"
def attempt_access; do_post; end如果您只需要登录,或者
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中
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发布于 2009-12-22 09:02:51
在不测试身份验证而是测试需要对用户进行身份验证的控制器时,我通常会使用stub filter方法:
before(:each) do
controller.stub!(:authenticate).and_return(true)
end上面的示例适用于将我的before_filter设置为authenticate方法的情况:
before_filter :authenticate我的应用程序中的身份验证使用HTTP基本身份验证,但它实际上可以是任何其他身份验证机制。
private
def authenticate
authenticate_or_request_with_http_basic do |user,password|
user == USER_NAME && password == PASSWORD
end
end我认为这是一种非常简单的测试方式。
发布于 2008-09-16 12:16:55
我找到了我自己问题的几个答案。基本上,我需要了解如何从restful_authentication模拟用户,以便即使我添加了before_filter: login_required,自动生成的rspec控制器测试也可以通过。
以下是我刚刚找到的一些资源:
RSpec: It Should Behave Like
rspec, restful_authentication, and login_required
using restful_authentication current_user inside controller specs
DRYing up your CRUD controller RSpecs
https://stackoverflow.com/questions/64827
复制相似问题