注释模型的Rspec测试(验证失败:用户必须存在)

时间:2018-08-16 08:21:39

标签: rspec rspec-rails

我有一个注释和用户模型的关联(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

当我测试上述注释模型时,它显示错误失败/错误:post {create(:post,user:user)}

 ActiveRecord::RecordInvalid:
   Validation failed: User must exist

1 个答案:

答案 0 :(得分:1)

将您的评论工厂定义为

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