gpt4 book ai didi

ruby-on-rails - RSpec 测试销毁操作

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

我正在尝试为我的嵌套评论 Controller 测试“销毁”操作。

用户模型 has_many :comments, dependent: :destroy电影模型 has_many :comments, dependent: :destroy评论模型 belongs_to :user 和 :movie这是我的评论 Controller

  def create
@comment = @movie.comments.new(comment_params.merge(user: current_user))

if @comment.save
flash[:notice] = 'Comment successfully added'
redirect_to @movie
else
flash.now[:alert] = 'You can only have one comment per movie'
render 'movies/show'
end
end

def destroy
@comment = @movie.comments.find(params[:id])

if @comment.destroy
flash[:notice] = 'Comment successfully deleted'
else
flash[:alert] = 'You are not the author of this comment'
end
redirect_to @movie
end

private

def comment_params
params.require(:comment).permit(:body)
end
def set_movie
@movie = Movie.find(params[:movie_id])
end

当然还有 before_action :set_movie, only: %i[create destroy] 在顶部。

这是我的规范,我使用的是 FactoryBot,所有工厂在其他示例中都运行良好,所以我认为问题出在其他地方。

  describe "DELETE #destroy" do
let(:user) { FactoryBot.create(:user) }
let(:movie) { FactoryBot.create(:movie) }
before do
sign_in(user)
end

it "deletes comment" do
FactoryBot.create(:comment, movie: movie, user: user)

expect do
delete :destroy, params { movie_id: movie.id }
end.to change(Comment, :count).by(-1)
expect(response).to be_successful
expect(response).to have_http_status(:redirect)
end
end

我有一个错误ActionController::UrlGenerationError: 没有路由匹配 {:action=>"destroy", :controller=>"comments", :movie_id=>1}我认为我在 specs destroy action 中的地址是错误的,但如何以一种好的方式定义它?

最佳答案

您需要指定要删除的评论的 ID:

it "deletes comment" do
comment = FactoryBot.create(:comment, movie: movie, user: user)

expect do
delete :destroy, params { id: comment.id, movie_id: movie.id }
end.to change(Comment, :count).by(-1)
# ...
end

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

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