What is the best way to handle testing of concerns when used in Rails 4 controllers? Say I have a trivial concern Citations.
module Citations
ex
My answer may look bit more complicated than these by @Benj and @Calin, but it has its advantages.
describe Concerns::MyConcern, type: :controller do
described_class.tap do |mod|
controller(ActionController::Base) { include mod }
end
# your tests go here
end
First of all, I recommend the use of anonymous controller which is a subclass of ActionController::Base, not ApplicationController neither any other base controller defined in your application. This way you're able to test the concern in isolation from any of your controllers. If you expect some methods to be defined in a base controller, just stub them.
Furthermore, it is a good idea to avoid re-typing concern module name as it helps to avoid copy-paste errors. Unfortunately, described_class is not accessible in a block passed to controller(ActionController::Base), so I use #tap method to create another binding which stores described_class in a local variable. This is especially important when working with versioned APIs. In such case it is quite common to copy large volume of controllers when creating a new version, and it's terribly easy to make such a subtle copy-paste mistake then.