【问题标题】:Patch routing error Rails 5 in test测试中的补丁路由错误 Rails 5
【发布时间】:2017-11-03 02:17:45
【问题描述】:

我不知道这个问题。使用宝石设计和全球化。 不知道是不是原因,但是form_for在html中生成了错误的动作,看看:

form class="edit_status" id="edit_status_1" action="/1/statuses/update" method="post" accept-charset="UTF-8"

Id 置于状态之前。我不知道为什么。

Form_for

form_for(@status, url:statuses_update_path(@status), method: :post) do |f|

设置方法发布,因为控制器在没有它的情况下接收 id = update

问题详情如下。

错误

No route matches {:action=>"/statuses/390022407", :controller=>"statuses", :status
=>{:content=>"Lorem ipsum"}}

Routes.db

Rails.application.routes.draw do
   scope "(:locale)", locale: /en|pl/ do
      post 'statuses/update'
      resources :statuses, only: [:update]
   end
end

铁路路线

控制器

class StatusesController < ApplicationController
    before_action :authenticate_user!
    before_action :set_locale

    def update
        #code...
    end

    private
        def status_params
            params.require(:status).permit(:content)
        end

        def set_locale
            I18n.locale = params[:locale] || I18n.default_locale
        end
end

测试代码

require 'test_helper'

class StatusesControllerTest < ActionController::TestCase
    include Devise::Test::ControllerHelpers

    def setup
        @user = users(:brock)
        @status = statuses(:statusBrock)
        I18n.default_locale = :en
    end

    test "should not update when not logged in" do
        patch status_path(@status), params: { status: { content: "Lorem ipsum" } }
        assert_redirected_to new_user_session_path
    end

    test "should update when logged in user admin" do
        sign_in @user
        patch status_path(@status), params: { status: { content: "Lorem ipsum" } }
        assert_equal "Lorem ipsum", @status.content 
    end
end

有什么东西不见了?

【问题讨论】:

    标签: ruby-on-rails testing devise routing ruby-on-rails-5


    【解决方案1】:

    我并不清楚你想做什么。

      post 'statuses/update'
      resources :statuses, only: [:update]
    

    您在此处定义了两条路由 - 一条是发布到 statuses/update 的帖子,它不需要额外的参数,第二条是 /status/status_id。

    然后你打电话

    statuses_update_path(@status)
    

    并将@status 作为参数传递给路径,除了该路由不接受 id 参数,它接受一个语言环境参数。

    您是否有理由希望路由是状态/更新而不是更 RESTful 的状态/?。我会删除第一条路线,并使用内置的 Rails 命名约定。

    编辑: 此外,在您的测试代码中,您只测试第二条路线 - 不清楚为什么您有这两条不同的路线并且您在它们之间切换。

    【讨论】:

    • 我对 RESTful 的研究最多,并更正了代码,删除了第一个路由并使用了 Rails 命名约定。我使用的是 post ajax,所以添加了错误的路由,因为 ajax 不起作用。但问题出在同一个 ajax 申请中。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多