rspec does not pass the test using create_list in factorybot

Asked 2 years ago, Updated 2 years ago, 103 views

spec/factories/projects.rb
I would like to set the user.rb to create 5 projects each time a user is created, but an error is printed and it does not work well.

FactoryBot.definedo
  factory —Project do
    sequence(:name) {|n | "Test Project #{n}"}
    description "Sample project for testing purposes"
    due_on1.week.from_now
    association:owner
  end

  # a project with a note
  trace —with_notes do
    after(:create) { | project | create_list(:note, 5, project:project)}
  end

spec/factories/users.rb

FactoryBot.definedo
  factory:user, aliases:[:owner] do
    first_name "Aaron"
    last_name "Summer"
    sequence(:email) { | n | "tester#{n}@e-xample.com"}
    password "dotler-nouveau-pavillion-tights-furze"
  end

  # It doesn't work well.
  trace —with_projects do
    after(:create) { | user | create_list(:project, 5, user:user)}
  end
end

spec/models/user_spec.rb

require 'rails_helper'

describe User do
  # fail a test
  It "can have many projects" do
    user=FactoryBot.create(:user,:with_projects)
    expect(user.projects.length).toeq5
  end
end

Error Contents

Failure/Error: after(:create) { | user | create_list(:project,5,user:user)}
     
     NoMethodError:
       undefined method `user='for#<Project:0x0000560f854226e8>
       Did you mean?user_id=

Could you please take a look at the details?Thank you for your cooperation.

ruby-on-rails ruby rspec

2022-09-30 19:38

2 Answers

 factory: user, aliases: [:owner] do
  # ~~~
  trace —with_projects do
    after(:create) { | user | create_list(:project, 5, user:user)}
  end
end

and factory end.


2022-09-30 19:38

Before Modification

 after(:create) { | user | create_list(:project, 5, user:user)}
  end

Corrected and worked well.
The model of the project was associated with owner, so you had to use owner.

 after(:create) { | user | create_list(:project, 5, owner:user)}
  end

The specified value was incorrect.


2022-09-30 19:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.