1
我使用Rails 4.2和Rspec 3.4。我有3個控制器測試,測試閃光消息以查看是否顯示正確的消息。其中兩人正在工作,一人不在。我看不出工作人員和不工作人員之間的區別。Rspec 3.4/Rails 4.2:在一個規範中測試Flash消息失敗,但不是其他兩個測試
我的控制器看起來是這樣的:
before_filter :logged_in_as_team_member, except: [:index, :show, :choose_revisions_to_diff, :diff_results]
def destroy
doc = Document.find(params[:id])
if doc.owners.include?(@user) && !doc.document_revisions.any?
doc.destroy
redirect_to documents_url, notice: "Document successfully deleted."
else
redirect_to documents_url, flash: { error: "Could not delete document because you are not an owner or the document has revisions assigned to it." }
end
end
private
def logged_in_as_team_member
redirect_to root_url, flash: { error: "You must be a Devcomm team member to perform this action." } unless @user.is_devcomm
end
我Rspec的是這樣的:
describe "DELETE #destroy" do
### This test fails
it "as devcomm when user is owner returns success" do
devcomm_user
delete :destroy, id: documents(:nonsecretdocument1)
expect(response).to redirect_to(action: :index)
expect(flash[:notice]).to match "Document successfully deleted."
end
### This test passes
it "as devcomm when user is not owner redirects to documents#index" do
devcomm_user
delete :destroy, id: documents(:nonsecretdocument2)
expect(response).to redirect_to(action: :index)
expect(flash[:error]).to match "Could not delete document because you are not an owner."
end
### This test passes
it "as nondevcomm redirects to root_url" do
nondevcomm_user
delete :destroy, id: documents(:nonsecretdocument2)
expect(response).to redirect_to(root_url)
expect(flash[:error]).to match "You must be a Devcomm team member to perform this action."
end
end
錯誤:
Failures:
1) DocumentsController DELETE #destroy as devcomm when user is owner returns success
Failure/Error: expect(flash[:notice]).to match "Document successfully deleted."
expected nil to match "Document successfully deleted."
# ./spec/controllers/documents_controller_spec.rb:114:in `block (3 levels) in <top (required)>'
任何人都可以看到,爲什麼第一次測試失敗,另外兩個傳球?
編輯添加:當我在用戶界面中刪除文檔時,閃光燈按預期顯示。
我發現測試您在控制器操作中修改的記錄很有幫助。在這種情況下,類似'expect{@record.reload}.to raise_error(ActiveRecord :: RecordNotFound)' –