2011-09-28 61 views
1

在解決練習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 

回答

1

我才意識到,我看您發佈的三個測試的一個錯誤(這將是更清楚,如果你只發布了失敗的測試:)

但是我很困惑,你"it should not self destruct"測試是完全一樣的爲"it should destroy the user"

it "should destroy the user" do 
    lambda do 
    delete :destroy, :id => @user 
    end.should change(User, :count).by(-1) 
end 

it "should not self-destruct" do 
    lambda do 
    delete :destroy, :id => @user.id 
    end.should change(User, :count).by(0) 
end 

您正在運行相同的測試兩次,但期待不同的結果。我會再看看「它不應該自毀」,看看你的意思(我不確定)。

我猜想需要改變的是`change(xxxx).by(0)中的任何內容。通過測試不應該改變什麼?

+0

你是對的,我花了一段時間纔看到我的方式錯誤。我從錯誤中出錯的地方並沒有將@admin聲明爲實例變量。我在原始問題中發佈的代碼並未表明這一點。感謝您的幫助! –

1

這咬了我很長一段時間了。嘗試從改變你的語法:

should change(User, :count).by(-1) 

到:

should change{ User.count }.by(-1) 

或嘗試這樣做的:

這變得有點從書本,但你可以嘗試改變你的語法。對於這種類型的期望的RSpec推薦是:

it "should destroy the user" do 
    expect{ 
    delete :destroy, :id => @user 
    }.to change{ User.count }.by(-1) 
end 

我真的認爲它更乾淨,更可讀無論如何。你能提供一個鏈接到這本書中的例子嗎?

+0

我做了更改,但它仍然返回相同的錯誤。 –

相關問題