我想测试控制器规范中的操作,但出于某种原因,我得到了无路径匹配错误。我应该做些什么来使路线起作用?rails + rspec控制器规范与多态关联
ActionController::UrlGenerationError:
No route matches {:action=>"create", :comment=>{:body=>"Consectetur quo accusamus ea.",
:commentable=>"4"}, :controller=>"comments", :post_id=>"4"}
模型
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true, touch: true
class Post < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
路由
resources :posts do
resources :comments, only: [:create, :update, :destroy], module: :posts
end
controller_spec
describe "POST create" do
let!(:user) { create(:user) }
let!(:profile) { create(:profile, user: @user) }
let!(:commentable) { create(:post, user: @user) }
context "with valid attributes" do
subject(:create_action) { xhr :post, :create, post_id: commentable, comment: attributes_for(:comment, commentable: commentable, user: @user) }
it "saves the new task in the db" do
expect{ create_action }.to change{ Comment.count }.by(1)
end
...
EDIT
从上面的controller_spec可以spec/controllers/comments_controller_spec.rb
控制器找到/ comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@comment = @commentable.comments.new(comment_params)
authorize @comment
@comment.user = current_user
if @comment.save
@comment.send_comment_creation_notification(@commentable)
respond_to :js
end
end
控制器/帖/ comments_controller.rb
class Posts::CommentsController < CommentsController
before_action :set_commentable
private
def set_commentable
@commentable = Post.find(params[:post_id])
end
最大,你是对的,我的路线可以使用没有嵌套更新/销毁。我用我的创建操作设置更新了我的答案。我会将注释创建代码保留在'CommentsController'中,而不是'Posts :: CommentsController',因为你可以在更新后的问题中看到。我也有产品评论,所以这样就可以在模块控制器中放置'set_post'或'set_product',我可以在'CommentsController'中保留create action的主要部分。你怎么看?你能告诉我,如果我有一半的代码在这里,一半可以测试吗?顺便说一句。在开发环境一切工作正常。 –
最大,请参阅我的prev评论。因此,我只是按照建议的创建操作嵌套我的控制器规范,并且结果如此。 THX –
不错,它解决了 - 请参阅我的编辑如何测试它的一些技巧。 – max