使用rspec中的条件检查Hasmanythrought

问题描述 投票:0回答:1
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测试

  it "should have many roles (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

但是该规范失败了,因为在这里不推荐使用conditions方法,如何在此处检查范围并通过“ roles.created_at> = 05-02-2020”来测试范围]

ruby-on-rails rspec3
1个回答
0
投票

您可以使用shoulda matchers gem,它为您提供了许多有用的匹配器。这是ActiveRecord匹配器用于has many关联。在您的情况下,它将很有用:

      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
© www.soinside.com 2019 - 2024. All rights reserved.