Dom*_*let 2 rspec ruby-on-rails mongodb mongoid
我有一个具有以下代码的 ArticleController:
def edit
@article = current_user.articles.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)
以及以下测试:
describe "GET 'edit'" do
it "should fail when signed in and editing another user article" do
sign_in @user
get :edit, :id => @another_user_article.id
response.should_not be_success
end
end
Run Code Online (Sandbox Code Playgroud)
但是,当我开始测试时,出现以下错误(这是正常的),但我想知道如何处理以便我的测试通过?
Failure/Error: get :edit, :id => @another_user_article.id
Mongoid::Errors::DocumentNotFound:
Document not found for class Article with id(s) 4f9e71be4adfdcc02300001d.
Run Code Online (Sandbox Code Playgroud)
我想通过这个改变我的控制器方法,但这对我来说似乎不对:
def edit
@article = Article.first(conditions: { _id: params[:id], user_id: current_user.id })
end
Run Code Online (Sandbox Code Playgroud)
您可以决定在这种情况下您的代码正确的做法是引发异常,因此将您的规范更改为
expect { get :edit, :id => @another_user_article.id}.to raise_error(Mongoid::Errors::DocumentNotFound)
Run Code Online (Sandbox Code Playgroud)
或者你可以决定你的控制器在这种情况下应该做什么是显式渲染 404: 在控制器级别(在操作中或通过rescue_from)拯救异常,在这种情况下你的规范应该按原样通过。