注释模型的Rspec测试(验证失败:用户必须存在)
我有一个评论和用户模型的关联(属于:user并且有很多:评论)。在注释中,它抛出了一个错误。 注释模型:注释模型的Rspec测试(验证失败:用户必须存在),rspec,rspec-rails,Rspec,Rspec Rails,我有一个评论和用户模型的关联(属于:user并且有很多:评论)。在注释中,它抛出了一个错误。 注释模型: class Comment < ApplicationRecord belongs_to :post belongs_to :user validates :post_id, presence: true validates :body, presence:true, length: {minimum: 4} end 用户工厂 require 'faker' FactoryBot.d
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :post_id, presence: true
validates :body, presence:true, length: {minimum: 4}
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)}
将您的注释工厂重新定义为
FactoryBot.define do
factory :comment do
body "sdfs dfjsdbf dsbfs"
post
user
end
end
在您的评论中_spec.rb
user = create :user
comment = create :comment, user: user
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
ActiveRecord::RecordInvalid:
Validation failed: User must exist
FactoryBot.define do
factory :comment do
body "sdfs dfjsdbf dsbfs"
post
user
end
end
user = create :user
comment = create :comment, user: user