Vishal
Vishal

Reputation: 717

How to write RSpec to check if associated record exists?

I am beginner to RSpec. I am having a model teacher that has_many :lessons. Here is my FactoryGirls records:

spec/factories/lessons.rb

FactoryGirl.define do
  factory :lesson do
    title "Rspec test"
    description "test description"
    company_name "narola pvt"
    association :teacher
    location "Zwanenplein 34"
    days_to_pay 2
  end
end

spec/factories/teachers.rb

FactoryGirl.define do
  factory :teacher do
    first_name "Teacher's name"
    last_name "Teacher's last name"
    address "los angeles"
    city "california"
    zip_code "12345"
    country "USA"
    birthdate nil
    phone nil
    password "password"
    email { "example#{SecureRandom.uuid}@email.dummy" }
  end
end

Following is my try with models test:

spec/models/teacher_spec.rb

require 'rails_helper'

RSpec.describe Teacher, type: :model do
  let(:teacher) { FactoryGirl.create(:teacher) }

  it "should have at least one lesson" do
    config.expect_with(Lesson.where(teacher_id: teacher)){|c| c.syntax = :should}
  end
end

I am willing to write a rspec test case to find if lesson exists for particular lesson.

Upvotes: 1

Views: 2902

Answers (2)

swag
swag

Reputation: 13

it "should have at least one lesson" do expect(Lesson.where(teacher_id: teacher.id).exists?).to be_truthy end This would be faster because of the use of 'exists?' method compared to expect(Lesson.where(teacher_id: teacher.id)).to exist

Underlying query execution due to use of 'exists?' the method is fast. More details are here -> https://www.ombulabs.com/blog/benchmark/performance/rails/present-vs-any-vs-exists.html

Upvotes: 0

Asmita
Asmita

Reputation: 183

Please try this:

it "should have at least one lesson" do
   expect(Lesson.where(teacher_id: teacher.id)).to exist    
end

Let me know if it's work for you. I haven't try this.

Upvotes: 1

Related Questions