我正在使用rspec + FactoryGirl来测试我的应用。
我有下一个测试
context "user cannot be destroyed" do
before(:each) do
@user = FactoryGirl.create :user
delete :destroy, {id: 1}, format: :json
end
it "render the json error when the user is not destroyed" do
user_response = JSON(response.body, symbolize_names: true)
expect(user_response[:errors][:message]).to include "User cannot be destroyed"
end
it {should respond_with 422}
end
当我运行测试时,我收到错误Couldn't find User with 'id'=1
两次。如果我更改了标识{id: @user.id}
,则测试未通过,我会收到下一个错误。
undefined method `[]' for nil:NilClass
和
Expected response to be a 422, but was 204
我测试的代码是
def destroy
user = User.find(params[:id])
if user.destroy
render json: {success: {:message => "User destroyed"} }, status: 204
else
render json: {errors: {:message => "User cannot be destroyed"} }, status: 422
end
end
所以,我有两个问题:
如果第二个问题是假的,我认为我的生活会更容易。
答案 0 :(得分:1)
这部分测试:
@user = FactoryGirl.create :user
delete :destroy, {id: 1}, format: :json
假设 @user
将被分配为ID 1
。这不是一个安全的假设。您将此行更改为:
delete :destroy, {id: @user.id}, format: :json
在更改之后,您说测试失败了:
Expected response to be a 422, but was 204
表示用户 已销毁。
最简单的解决方案是更换控制器:
def destroy
user = User.find(params[:id])
render json: {errors: {:message => "User cannot be destroyed"} }, status: 422
end
在现实世界中,也许有些用户可以被销毁的情况,在这种情况下,您需要在控制器中使用某些逻辑。