DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

1 2

Concern | split, and spin-off, share the responsibility in Rails

🦄 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.


🔗 Parent Note

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post