Rspec 测试评论模型(验证失败:用户必须存在)

Rspec testing for comment model ( Validation failed: User must exist)

我有一个评论和用户模型的关联(belongs_to :user 和 has_many :comments)。在 comment_spec 它抛出一个错误。 评论模特:

class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :post_id, presence: true
validates :body, presence:true, length: {minimum: 4}
end

帖子模型

class Post < ApplicationRecord
validates :title, presence: true, length: {minimum: 3}
validates :body, presence: true
has_many :comments, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :ratings
end

用户模型

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :comments
end

评论工厂

FactoryBot.define do
factory :comment do
body "sdfs dfjsdbf dsbfs"
post {create(:post)}
user_id {create (:user)}
end
end

用户工厂

require 'faker'
FactoryBot.define do
factory :user do
email {Faker::Internet.email}
password "123456"
end
end

评论模型规格

  require 'rails_helper'
  RSpec.describe Comment, type: :model do
  describe "validations" do
  describe "it is not present" do
  let(:comment) {build(:comment,body:'')}
  it 'should be invalid' do
    expect(comment.valid?).to be_falsey
  end
end

describe "it does not have minimum 3 char" do
  let(:comment) {build(:comment,body:'12')}
  it 'should be invalid' do
    expect(comment.valid?).to be_falsey
  end
end
end

 describe "It is under a post" do
 let(:comment) {build(:comment)}
 it "it belongs to a post " do
   expect(comment.post).to be_truthy
 end
end
end

当我测试上面的评论模型时它显示错误 Failure/Error: post {create(:post, user: user)}

 ActiveRecord::RecordInvalid:
   Validation failed: User must exist

将您的评论工厂重新定义为

FactoryBot.define do
  factory :comment do
    body "sdfs dfjsdbf dsbfs"
    post
    user
  end
end

在你的comment_spec.rb

user = create :user
comment = create :comment, user: user