【问题标题】:How to write RSpec to check if associated record exists?如何编写 RSpec 来检查关联记录是否存在?
【发布时间】:2017-11-09 08:58:41
【问题描述】:

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

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

以下是我对模型测试的尝试:

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

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

【问题讨论】:

    标签: ruby-on-rails rspec associations


    【解决方案1】:

    请试试这个:

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

    让我知道它是否适合你。这个我没试过。

    【讨论】:

    • 非常感谢您的努力。它对我有用。而且我也尝试了以下方式,并且有效。 :) expect(teacher.lessons).to be_present
    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多