我正在關注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