Rails、Restful 身份验证和RSpec - 如何测试需要身份验证的新模型
我使用 Bort 创建了一个学习应用程序,这是一个包含 Restful Authentication 和 RSpec 的基础应用程序.我已经启动并运行并添加了一个新对象,该对象要求用户先登录才能执行任何操作(before_filter :login_required
在控制器中).
I've created a learning application using Bort, which is a base app that includes Restful Authentication and RSpec. I've got it up and running and added a new object that requires users to be logged in before they can do anything(before_filter :login_required
in the controller). [edit: I should also mention that the user has_many
of the new class and only the user should be able to see it.]
我使用 Rspec 的生成器创建了新模型/控制器,这些生成器创建了许多默认测试.如果没有 before_filter
,它们都会通过,但正如预期的那样,一旦 before_filter
就位,它们都会失败.
I've created the new model/controller using Rspec's generators which have created a number of default tests. They all pass if there is no before_filter
but several fail, as should be expected, once the before_filter
is in place.
如何让生成的测试像有/没有登录用户一样运行?我是否需要一整批未登录的匹配项 - 重定向测试?我认为这是某种模拟或固定技术,但我是 RSpec 的新手并且有点飘忽不定.好的 RSpec 教程链接也将不胜感激.
How do I get the generated tests to run as if there is/is not a logged in user? Do I need a whole batch of matching not logged in - redirect tests? I assume it is some sort of mocking or fixture technique but I am new to RSpec and a bit adrift. Good RSpec tutorial links would also be appreciated.
我有一个非常相似的设置,下面是我目前用来测试这些东西的代码.在我输入的每个 describe
中:
I have a very similar setup, and below is the code I'm currently using to test this stuff. In each of the describe
s 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