在解決練習5時,我碰到類似的問題,與此question。我重構基礎上給出這個問題的答案,但我仍然接受失敗:Rails 3教程Ch。 10.6 ex 5 rspec失敗
1) UsersController DELETE 'destroy' as an admin user should not self-destruct
Failure/Error: lambda do
count should have been changed by 0, but was changed by -1
# ./spec/controllers/users_controller_spec.rb:354:in `block (4 levels) in <top (required)>'
我的規格:
it "should destroy the user" do
lambda do
delete :destroy, :id => @user
end.should change(User, :count).by(-1)
end
it "should redirect to the users page" do
delete :destroy, :id => @user
response.should redirect_to(users_path)
end
it "should not self-destruct" do
lambda do
delete :destroy, :id => @user.id
end.should change(User, :count).by(0)
end
和我的控制器:
def destroy
@user = User.find(params[:id])
if current_user == @user
flash[:notice] = "You cannot destroy yourself"
else
@user.destroy
flash[:success] = "User destroyed"
end
redirect_to users_path
end
我已檢查在瀏覽器中的行爲,並按預期工作。一如往常,任何幫助表示讚賞。謝謝!
更新,工作代碼:
describe "as an admin user" do
before(:each) do
@admin = Factory(:user, :email => "[email protected]", :admin => "true")
test_sign_in(@admin)
end
it "should have links to destroy a user" do
get :index
response.should have_selector("a", :content => "delete")
end
it "should destroy the user" do
lambda do
delete :destroy, :id => @user
end.should change{ User.count }.by(-1)
end
it "should redirect to the users page" do
delete :destroy, :id => @user
response.should redirect_to(users_path)
end
it "should not be allowed to delete itself" do
lambda do
delete :destroy, :id => @admin
end.should_not change{ User.count }
end
end
你是對的,我花了一段時間纔看到我的方式錯誤。我從錯誤中出錯的地方並沒有將@admin聲明爲實例變量。我在原始問題中發佈的代碼並未表明這一點。感謝您的幫助! –