π¦ Code Template
Make mogera
logic into the concern.
# lib/fuga/piyo.rb ( you can make it inside of the lib π) module Fuga::Piyo extend ActiveSupport::Concern def mogera # do something... end end
Then, include the mogera
method.
# hoge.rb class Hoge < ActiveRecord::Base include Fuga::Piyo end
β Testing
Write the test code for the mogera
and the piyo
module as shared_examples_for
.
By building the model from metaprogramming, you can call the model which includes this concern from this concern test. ( The power of the metaprogramming π )
# spec/lib/fuga/piyo_spec.rb require 'rails_helper' shared_examples_for 'piyo' do let(:model_name) { described_class.to_s.underscore.gsub(/\//,'_').to_sym } let(:model) { build(model_name)} describe 'mogera' do # test code end end
Enable to load the test files.
# spec/rails_helper.rb Dir[Rails.root.join('spec/lib/**/*.rb')].each { |f| require f }
Include it via rails_helper
and test it at it behaves_like.
# spec/hoge_spec.rb require 'rails_helper' describe V3::ContactRequest do # I recommend to split this test from others to test it isolated. ( `rspec spec/hoge_spec.rb -e 'includes'` describe 'includes' do it_behaves_like 'piyo' end end
Then, test it.
bundle exec rspec spec/hoge_spec.rb -e 'includes'
In this way, you can test this concern at each model which includes the concern.
Top comments (0)