我是Rails的新手,试图测试batiment的创建以及此创建的showbatiment页面的重定向。

batiments_controller_test.rb

test "should create batiment" do
 post :create, batiment: {nom: "New batiment"}
 assert_response :success
 assert_redirected_to assigns(:batiment)
end


batiments_controller.rb

def create
  @batiment = Batiment.new(batiment_params)
 if @batiment.save
  flash[:notice] = "Bâtiment créé!"
  redirect_to @batiment
 else
  render('new')
 end
end


路线

                   POST   /batiments(.:format)                              batiments#create
   new_batiment GET    /batiments/new(.:format)                          batiments#new
  edit_batiment GET    /batiments/:id/edit(.:format)                     batiments#edit
       batiment GET    /batiments/:id(.:format)                          batiments#show


运行测试时的终端:

     1) Error:
BatimentsControllerTest#test_should_create_batiment:
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"batiments", :id=>nil} missing required keys: [:id]
    test/controllers/batiments_controller_test.rb:25:in `block in <class:BatimentsControllerTest>'

最佳答案

当然,无法创建标题,因此该动作呈现了视图'new'。这就解释了为什么assert_response :success通过了(请求返回了http代码200),以及为什么assert_redirected_to assigns(:batiment)失败了(没有保存batiment,因此没有id)。

检查为什么保存失败(也许验证失败?请检查@batiment.errors),然后像这样重写测试:

test 'should create batiment' do
 assert_difference('Batiment.count') do
   post :create, batiment: {nom: 'New batiment'}
 end
 assert_redirected_to assigns(:batiment)
end

09-25 16:46