我正在关注Michael Hartl关于Ruby on Rails的优秀教程。我卡住试图了解的方式ActionDispatch :: Response的作品。这源自第9章的练习9(Rails版本3.2.3)。Rails response.should be_success永远不是真的
特别是我们被要求确保用户自己无法User#destroy
这个管理员。我有一个想法如何做到这一点,但因为我试图遵循TDD方法论,所以我首先编写测试。
这是在我的测试的相关片段:
describe "authorization" do
describe "as non-admin user" do
let(:admin) {FactoryGirl.create(:admin)}
let(:non_admin) {FactoryGirl.create(:user)}
before{valid_signin non_admin}
describe "submitting a DELETE request to the Users#destroy action" do
before do
delete user_path(admin)
#puts response.message
puts response.succes?
end
specify{ response.should redirect_to(root_path) }
specify{ response.should_not be_success }
end
end
#Exercise 9.6-9 prevent admin from destroying himself
describe "as admin user" do
let(:admin){FactoryGirl.create(:admin)}
let(:non_admin){FactoryGirl.create(:user)}
before do
valid_signin admin
end
it "should be able to delete another user" do
expect { delete user_path(non_admin) }.to change(User, :count).by(-1)
end
describe "can destroy others" do
before do
puts admin.admin?
delete user_path(non_admin)
puts response.success?
end
#specify{response.should be_success}
specify{response.should_not be_redirect}
end
describe "cannot destroy himself" do
before do
delete user_path(admin)
puts response.success?
end
#specify{response.should_not be_success}
specify{response.should be_redirect}
end
end
.
.
.
end
所有的测试都通过了,除了"can destroy others"
测试。
然而,如果我puts response.success?
每delete
请求后,我总是得到False
,所以没有请求的“成功”。
手动与webapp进行交互并删除用户工作得很好,所以我认为response.success
并不意味着detroy
(或任何其他要求)不成功,而是别的。我读到它与HTTP响应200/302/400之间的差异,但我不完全确定。
根据记录,这是我的User#destroy
:
def destroy
User.find(params[:id]).destroy
flash[:success]="User destroyed."
redirect_to users_path
end
任何光对此有何看法? 谢谢!
编辑
这是我厂:
FactoryGirl.define do
factory :user do
sequence(:name){ |n| "Person #{n}" }
sequence(:email){ |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
factory :admin do
admin true
end
end
end
编辑2通过@Peter Alfvin的建议,我改线
let(:user){FactoryGirl.create(:user)}
到
let(:admin){FactoryGirl.create(:admin)}
以及全部user
至admin
。我还在delete
请求之前添加了一个puts admin.admin?
。还是行不通!
编辑3
改变测试"can destroy others"
为:
describe "can destroy others" do
before do
puts admin.admin?
delete user_path(non_admin)
puts response.success?
end
#specify{response.should be_success}
specify{response.should_not be_redirect}
end
似乎并没有帮助的。
我的问题的解决方案可以在后续的这里找到:http://stackoverflow.com/a/19013924/1338339 – lllllll