簡體   English   中英

檢查 has_many :通過 rspec 中的條件

[英]Checking has_many :through with the conditions in rspec

class Company
  has_many :permissions
  has_many :roles,->{where("roles.created >= ?",Date.today-1.day)}through: :permissions
end

class Role
  has_many :permissions
  has_many :companies,through: :permissions
end

class Permission
  belongs_to :role
  belongs_to :company
end

這種情況怎么做rspec測試它應該有很多作用

(roles.created_at >= Date.today-1.day)" do
    ass = Company.reflect_on_association(:roles)
    ass.macro.should == :has_many
    ass.options.should == {
      :through => :permissions,
      :conditions => "roles.created_at >= 05-02-2020",
    }
  end

但是規范失敗了,因為這里不推薦使用條件方法如何在這里檢查范圍並通過 where 子句"roles.created_at >= 05-02-2020"測試范圍

您可以使用shoulda matchers gem ,它為您提供了許多有用的匹配器。 這里有許多關聯的 ActiveRecord 匹配器。 在您的情況下,它將很有用:

class Person < ActiveRecord::Base
  has_many :coins, -> { where(quality: 'mint') }
end

# RSpec
RSpec.describe Person, type: :model do
  it { should have_many(:coins).conditions(quality: 'mint') }
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM