gpt4 book ai didi

ruby-on-rails - Rspec:测试嵌套销毁操作

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:42 27 4
gpt4 key购买 nike

我正在尝试为我的嵌套评论 Controller 测试“销毁”操作。 发表 has_many 评论。我之前遇到过类似的问题,明白我需要传递一个id,但我仍然遇到一个非常熟悉的错误......

Failures:

1) CommentsController#DELETE destroy deletes a comment
Failure/Error: delete :destroy, comment: create(:comment), post_id: @post
ActionController::UrlGenerationError:
No route matches {:action=>"destroy", :comment=>"1", :controller=>"comments", :post_id=>"1"}
# ./spec/controllers/comments_controller_spec.rb:19:in `block (3 levels) in <top (required)>'

comments_controller_spec.rb

RSpec.describe CommentsController, :type => :controller do
before :each do
@post = FactoryGirl.create(:post)
end


....


describe '#DELETE destroy' do
it 'deletes a comment' do
delete :destroy, comment: create(:comment), post_id: @post
expect(response).to redirect_to post_path
end
end
end

comments_controller.rb

def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])

@comment.destroy
redirect_to post_path(@post)
end

routes.rb

 resources :posts do
resources :comments
end

rake 路

☹ rake routes
Prefix Verb URI Pattern Controller#Action
root GET / posts#index
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PATCH /posts/:post_id/comments/:id(.:format) comments#update
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy

最佳答案

你要请求的路由是这样的:

/posts/:post_id/comments/:id(.:format)

但是您要发送以下参数:

{:action=>"destroy", :comment=>"1", :controller=>"comments", :post_id=>"1"

您需要将 comment.id 作为 id 参数发送。

试试这个:

describe '#DELETE destroy' do
it 'deletes a comment' do
comment = create(:comment)
@post.comments << comment
# Also, test if the action really deletes a comment.
expect{delete :destroy, id: comment.id, post_id: @post}.
to change{@post.comments.count}.by(-1)
expect(response).to redirect_to post_path
end
end

关于ruby-on-rails - Rspec:测试嵌套销毁操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29087023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com