複数のクラスに共通するscopeがあるとき、moduleとして共通化する。
##before
author.rb
class Author < ApplicationRecord
scope :active, -> { where(state: 'active') }
end
book.rb
class Book < ApplicationRecord
scope :active, -> { where(state: 'active') }
end
##after
models/concerns/active_scope.rb
module ActiveScope
extend ActiveSupport::Concern
included do
scope :active, -> { where(state: 'active') }
end
end
author.rb
class Author < ApplicationRecord
include ActiveScope
end
book.rb
class Book < ApplicationRecord
include ActiveScope
end
##RSpec
モデルと同じようにテストする
spec/models/active_scope_spec.rb
require 'rails_helper'
RSpec.describe ActiveScope, type: :model do
describe '#active' do
it '' do
...
end
end
end
##参考