【问题标题】:Rspec testing for comment model ( Validation failed: User must exist)评论模型的 Rspec 测试(验证失败:用户必须存在)
【发布时间】:2018-08-16 08:21:38
【问题描述】:

我有一个评论关联和用户模型(belongs_to :user 和 has_many :cmets)。在 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

【问题讨论】:

    标签: rspec rspec-rails


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多