测试Rails 4控制器

我在理解我的测试错误时遇到了一些麻烦,但在测试控制器的更新方法时,我一直没有获得路由匹配。 但是,通过浏览器提交表单是有效的。

我的路线文件:

namespace :merchant do resources :users get '/signup', to: "users#new" end 

我的控制器:

 def update respond_to do |format| if @merchant_user.update(user_params) format.html { redirect_to @merchant_user, notice: 'User was successfully updated.' } format.json { head :no_content } else format.html { render action: 'show' } format.json { render json: @merchant_user.errors, status: :unprocessable_entity } end end end 

我的测试:

 test "should update user" do user = users(:jon) user.first_name="Jonas" put :update, :merchant_user =>user.attributes assert_response :success 

结束

结果:

 1) Error: Merchant::UsersControllerTest#test_should_update_user: ActionController::UrlGenerationError: No route matches {:merchant_user=> {"id"=>"846114006", "email"=>"jon.sims@whatever.com", "first_name"=>"Jonas", "last_name"=>"Sims", "password_digest"=>"$2a$10$LVbV7pkd7li8sobYEauoS.4JVA2ZHzAXgPFbyiojYqgcDBHUE9bXW", "type"=>"Merchant::User", "created_at"=>"2013-07-11 22:59:41 UTC", "updated_at"=>"2013-07-11 22:59:41 UTC"}, :controller=>"merchant/users", :action=>"update"} test/controllers/merchant/users_controller_test.rb:45:in `block in ' 

任何提示?

从您的路线看起来的方式来看,它似乎期待一个id参数。

如果您从命令行执行rake routes ,它可能会显示一个类似的路由

/merchant/users/:id/update

如果你传入这样的id put :update, id: user.id, merchant_user: user.attributes它应该可以工作。

您需要传入用户的id才能使测试正确运行。

试试这个:

 put :update, id: user.id, merchant_user: {} 

您看到此错误,因为路由器需要resource/:id ,但您没有传递id。

Users#update是一个成员操作,需要一个id。 路由器需要用户id param: /users/:id/update 。 如果没有id,该方法无法找到您要更新的用户。