【问题标题】:Rails Testing redirection in controller create methodRails 在控制器创建方法中测试重定向
【发布时间】:2014-04-26 20:33:01
【问题描述】:

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

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>'

【问题讨论】:

    标签: ruby-on-rails unit-testing redirect testing ruby-on-rails-4


    【解决方案1】:

    当然无法创建 batiment,因此该操作渲染了视图 '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
    

    【讨论】:

    • 你完全正确,这是验证失败。我觉得我好笨。非常感谢
    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多