我測試我的應用程序以創建一個新的用戶汽車,稍後用戶創建新汽車應用程序必須重定向到user_car_path(我發佈我的路線) :lambda do count應該已經被改變了1,但被改變了0
user_cars GET /users/:user_id/cars(.:format) cars#index
POST /users/:user_id/cars(.:format) cars#create
new_user_car GET /users/:user_id/cars/new(.:format) cars#new
edit_user_car GET /users/:user_id/cars/:id/edit(.:format) cars#edit
user_car GET /users/:user_id/cars/:id(.:format) cars#show
PUT /users/:user_id/cars/:id(.:format) cars#update
DELETE /users/:user_id/cars/:id(.:format) cars#destroy
所以我測試我的應用程序與此rspec的:
describe "POST 'create' car" do
describe "car created success" do
before(:each) do
@user = User.create!(:email => "[email protected]", :password => "foobar", :password_confirmation => "foobar")
@car = Car.create!(:brand => "example", :color => "foobar", :model => "foobar", :year =>"2012")
end
it "should create a car" do
lambda do
post :create, :cars => @car, :user_id => @user.id
end.should change(Car, :count).by(1)
end
it "should redirect to the user cars page" do
post :create, :cars => @car, :user_id => @user.id
response.should redirect_to user_car_path(@user, @car)
end
end
end
,但我得到了2個錯誤
Failures:
1) CarsController POST 'create' car car created success should create a car
Failure/Error: lambda do
count should have been changed by 1, but was changed by 0
# ./spec/controllers/car_controller_spec.rb:20
2) CarsController POST 'create' car car created success should redirect to the user cars page
Failure/Error: response.should redirect_to user_car_path(@user, @car)
Expected response to be a redirect to <http://test.host/users/115/cars/40> but was a redirect to <http://test.host/users/115/cars/new>.
# ./spec/controllers/car_controller_spec.rb:27
,但我的應用程序正常工作;這裏是我的CarController
class CarsController < ApplicationController
....
def create
@user = User.find(params[:user_id])
@car = @user.cars.build(params[:car])
if @car.save
redirect_to user_car_path(@user, @car), :flash => { :notice => " car created!" }
else
redirect_to new_user_car_path ,:flash => { :notice => " sorry try again :(" }
end
end
def show
@user = User.find(params[:user_id])
@car = @user.cars.find(params[:id])
end
....
你已經創建了車(它保存到數據庫)在你之前的步驟中,所以我猜它不會再被創建。嘗試使用'@car = Car.new(...)'而不是'@car = Car.create!(...)'看看是否有幫助。 – Frost 2012-08-03 15:30:35
謝謝你的回答,你能更清楚地解釋我嗎?我在哪裏創造了汽車?我開始使用rspec – Asantoya17 2012-08-03 15:38:03
@ Asantoya17在自己的代碼中查看'@car = Car.create!',並閱讀rails文檔,瞭解爲什麼'create!'與'new'不同。這不是一個rspec的事情。 – radixhound 2012-08-03 15:44:47