Rails RSpec测试-防止删除不是其作者的用户的注释

时间:2018-12-19 21:20:55

标签: ruby-on-rails rspec

我正在尝试测试嵌套注释控制器的“破坏”操作。

在我的filmweb应用中,我具有范围和验证功能,可以防止用户删除不是作者的评论。在网络版本中,一切正常,但我不知道如何测试这种情况。

这是我的comments_controller

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

评论模型

class Comment < ApplicationRecord
 belongs_to :user
 belongs_to :movie

 validates :body, presence: true
 validates :user, :movie, presence: true
 validates :user, uniqueness: { scope: :movie }

 scope :persisted, -> { where.not(id: nil) }
end

用户模型has_many :comments, dependent: :destroy电影模型has_many :comments, dependent: :destroy。 我正在使用devise和FactoryBot,规格在这里:

describe "DELETE #destroy" do
  let(:user) { FactoryBot.create(:user) }
  let(:movie) { FactoryBot.create(:movie) }
  let(:other_user) { FactoryBot.create(:user, user_id: 100)}

  it "doesn't delete comment" do
    sign_in(other_user)
    comment = FactoryBot.create(:comment, movie: movie, user: user)

    expect do
      delete :destroy, params: { id: comment.id, movie_id: movie.id }
    end.to_not change(Comment, :count)
    expect(flash[:alert]).to eq "You are not the author of this comment"
  end
end

我遇到了一个错误undefined method `user_id=' for #<User:0x00007fb049644d20>,不知道这样做的好方法是什么。

=== EDIT ===

这是我的FactoryBot

FactoryBot.define do
  factory :user do
    email { Faker::Internet.email }
    password "password"
    confirmed_at 1.day.ago
  end

  factory :unconfirmed_user do
    email { Faker::Internet.email }
    password "password"
  end
end

1 个答案:

答案 0 :(得分:2)

问题在于,users表没有要在other_user实例中尝试使用的user_id列,该列的名称仅为id

let(:other_user) { FactoryBot.create :user, id: 100 } 

您可以完全省略ID,它将自动获得其他ID:

let(:other_user) { FactoryBot.create :user }