2017-07-15 123 views
0

我正在構建一個測試應用程序,允許用戶創建/刪除帖子。我在我的銷燬行爲中遇到了一個錯誤,我發現它很難調試。下面是我的測試:RSpec控制器銷燬測試

describe '#destroy' do 
    context 'existing post' do 
     let (:post) { FactoryGirl.create(:post) } 

     it 'removes post from table' do 
     expect { delete :destroy, id: post }.to change { Post.count }.by(-1) 
     end 

     it 'renders index template' do 
     delete :destroy, id: post 
     expect(response).to render_template('index') 
     end 
    end 

    context 'delete a non-existent post' do 
     it 'creates an error message' do 
     delete :destroy, id: 10000 
     expect(flash[:errors]).to include("Post doesn't exist") 
     end 
    end 
    end 

這裏是我的毀滅行動:

def destroy 
    @post = Post.find_by(id: params[:id]) 
    if @post 
     @post.destroy 
    else 
     flash[:errors] = "Post doesn't exist" 
    end 
    render :index 
    end 

我把一個調試器的作用,它看起來像帖子被發現,正確刪除,所以我懷疑問題是與我正在評估測試的方式。這是我的失敗規格:

1) PostsController#destroy existing post removes post from table 
    Failure/Error: expect { delete :destroy, id: post }.to change { Post.count }.by(-1) 
     expected result to have changed by -1, but was changed by 0 

這是怎麼回事?

回答

1

我認爲您的帖子已創建,但在第一次計數後進行評估。讓我們保證它以前創建let!

let!(:post) { FactoryGirl.create(:post) } 
+0

我明白,讓!在每個示例之前強制創建,而不是延遲加載。然而,當我在我的測試中調用'post'方法時應調用該方法。那麼它不會被創建,然後被刪除,那麼計數被評估? – Sunny