简体   繁体   English

"RSpec 测试破坏动作"

[英]RSpec testing destroy action

I'm trying to test the 'destroy' action for my nested comments controller.我正在尝试为我的嵌套评论控制器测试“销毁”操作。

User model has_many :comments, dependent: :destroy<\/code> Movie model has_many :comments, dependent: :destroy<\/code> Comments model belongs_to :user and :movie<\/code> Here is my comments controller用户模型has_many :comments, dependent: :destroy<\/code>电影模型has_many :comments, dependent: :destroy<\/code>评论模型belongs_to :user and :movie<\/code>这是我的评论控制器

  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

You need to specify id of a comment you want to remove:您需要指定要删除的评论的 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

I want to contribute here with one more approach.我想用另一种方法在这里做出贡献。 Sometimes you have to be sure that you've deleted the exact instance (comment_1, not comment_2).有时,您必须确保删除了确切的实例(comment_1,而不是 comment_2)。

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

  delete :destroy, params { id: comment_1.id, movie_id: movie.id }

  expect { comment_1.reload }.to raise_error(ActiveRecord::RecordNotFound)
  # ...
end

Somehow I was never able to pass an ID, either in params {} or as a direct argument following "delete".不知何故,无论是在参数 {} 中还是作为“删除”之后的直接参数,我都无法传递 ID。 Instead, I made it work like so:相反,我让它像这样工作:

it "DELETE will cause an exception" do
  delete "/comments/#{comment.id}"
  expect { comment.reload }.to raise_error(ActiveRecord::RecordNotFound)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM