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”来测试范围]
您可以使用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