I am new to RSpec (not very experienced yet with RoR neither!)
I am working on a web app where I have a Course model. To create a new Course I need to use Teacher and Student objects.
I want to create a test on the Course model and for that I am trying to use instance_double to mock Teacher and Student. Here is my code
require 'rails_helper'
RSpec.describe Course, type: :model do
it 'can be created' do
# creating the teacher
john = instance_double(Teacher)
allow(john).to receive(:save).and_return(true)
allow(john).to receive(:id).and_return(1)
# creating the student
francois = instance_double(Student)
allow(francois).to receive(:save).and_return(true)
allow(francois).to receive(:id).and_return(1)
# creating the course
testCourse = Course.new(teacher: john, student: francois, class_language: "EN")
# testing the course
expect(testCourse).to be_valid
end
end
I get the next failure from RSpec
1) Course can be created
Failure/Error: testCourse = Course.new(teacher: john, student: francois, class_language: "EN")
ActiveRecord::AssociationTypeMismatch:
Teacher(#70253947615480) expected, got #<Double Teacher(id: integer, email: string, encrypted_password: string, first_name: string, last_name: string, about: text, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, created_at: datetime, updated_at: datetime)> which is an instance of RSpec::Mocks::Double(#70253946301600)
# ./spec/models/course_spec.rb:16:in `block (2 levels) in <top (required)>'
Finished in 0.02549 seconds (files took 2.87 seconds to load)
1 example, 1 failure
My understanding is that ActiveRecord error is being caused by trying to associate a instance_double teacher and user with a course that expects a "real" teacher and student to be associated.
I have been trying many different ways, faking ID (see my code), or calling the models (see article here) themselves with
require 'student'
require 'teacher'
I saw this Stackoverflow post about similar issue, so I used non-deprecated syntax and it still doesn't work.
Any idea? Thanks!
Aucun commentaire:
Enregistrer un commentaire