如何编写RSpec来检查相关记录是否存在?

时间:2017-11-09 08:58:42

标签: ruby-on-rails rspec associations

我是RSpec的初学者。我的模型teacher has_many :lessons。这是我的FactoryGirls记录:

规格/工厂/ 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

规格/工厂/ 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

以下是我的模特测试:

规格/模型/ 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

我愿意写一个rspec测试用例来查找特定课程是否存在课程。

2 个答案:

答案 0 :(得分:1)

请试试这个:

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

让我知道它是否适合您。我没试过。

答案 1 :(得分:0)

it "should have at least one lesson" do expect(Lesson.where(teacher_id: teacher.id).exists?).to be_truthy end 由于使用“存在”,这会更快。方法相比 expect(Lesson.where(teacher_id: teacher.id)).to exist

由于使用“存在”而在底层执行查询?该方法是快速的。更多详细信息在这里-> https://www.ombulabs.com/blog/benchmark/performance/rails/present-vs-any-vs-exists.html