这是 Rails 4 中为销毁操作自动生成的测试,作为以下规范的一部分vehicles_controller.rb
:
describe "DELETE destroy" do
it "destroys the requested vehicle" do
vehicle = Vehicle.create! valid_attributes
expect {
delete :destroy, {:id => vehicle.to_param}, valid_session
}.to change(Vehicle, :count).by(-1)
end
it "redirects to the vehicles list" do
vehicle = Vehicle.create! valid_attributes
delete :destroy, {:id => vehicle.to_param}, valid_session
response.should redirect_to(vehicles_url)
end
end
这是我在控制器中得到的,同样非常标准:
def destroy
@vehicle = Vehicle.find(params[:id])
@vehicle.destroy
flash[:notice] = "Vehicle has been deleted"
redirect_to vehicles_url
end
这在应用程序本身中工作得很好——当您删除车辆时,它会重定向回 Vehicles_url,并且该条目会从数据库中删除。服务器日志看起来也完全正常。但是,当我运行规范时,它们失败如下:
1) VehiclesController DELETE destroy destroys the requested vehicle
Failure/Error: expect {
count should have been changed by -1, but was changed by 0
# ./spec/controllers/vehicles_controller_spec.rb:148:in `block (3 levels) in <top (required)>'
2) VehiclesController DELETE destroy redirects to the vehicles list
Failure/Error: response.should redirect_to(vehicles_url)
Expected response to be a redirect to <http://test.host/vehicles> but was a redirect to <http://test.host/>.
Expected "http://test.host/vehicles" to be === "http://test.host/".
# ./spec/controllers/vehicles_controller_spec.rb:156:in `block (3 levels) in <top (required)>'
谁能指出我这里可能发生了什么导致测试失败?谢谢你的帮助!
编辑:这里有一些关于之前过滤器可能会影响事物的附加信息。在车辆控制器中,由于我使用的是宝石 CanCan,所以我load_and_authorize_resource
在顶部。这个控制器也正在测试创建和更新的能力,并且这些规范正在通过,所以我认为这没有干扰,而且它没有因任何与权限有关的消息而失败。也许我需要更改let(:valid_session) { {} }
控制器规范顶部的默认设置?我不理会它,因为正如我所说,除了删除之外的所有其他操作都很好。
进一步编辑:根据下面提供的链接,我将我的规范编辑为:
describe "DELETE destroy" do
it "destroys the requested vehicle" do
vehicle = Vehicle.create! valid_attributes
expect {
delete :destroy, :id => vehicle.to_param, valid_session
}.to change(Vehicle, :count).by(-1)
end
it "redirects to the vehicles list" do
vehicle = Vehicle.create! valid_attributes
delete :destroy, :id => vehicle.to_param, valid_session
response.should redirect_to(vehicles_url)
end
end
现在,如果我尝试运行规范,我会收到以下语法错误:
/home/kathryn/testing/spec/controllers/vehicles_controller_spec.rb:150: syntax error, unexpected '\n', expecting => (SyntaxError)
第 150 行是指第一个规范中以 开头的行delete :destroy
,其中进行了更改。