Concerns are a new feature that was added in Rails 4. They allow to clean up code in your models and controllers. They also allow you to share functionality between models or controllers. However, they can be a bit tricky to test in isolation. In this article I want to show how you can test your controller concerns in isolation.

The Over Simplified Scenario

We have a project with several different types of objects that can be sold. Each item is unique and is marked as ‘out of stock’ once it is purchased. However, we have several different controllers and different types of purchases that need this functionality. In order to reduce code duplication, we are going to put these in a concern.

/app/controllers/concerns/transaction_processing.rb

 
module TransactionProcessing
extend ActiveSupport::Concern included do
helper_method :process_sale
end def process_sale(item)
item.is_in_stock = false
item.save!
end
end

If we want to test this concern, we need a controller to include it in. However, it would not be accurately unit testing to do this as there could be code in that controller that could affect the output of our test. Inside of our test, we can create a fake controller with no methods or logic of it’s own, and then write tests for that. If you are using RSpec , you can call methods directly using the subject object. Here is my example test using RSpec and FactoryGirl

/spec/controllers/concerns/transaction_processing_spec.rb

 
require 'spec_helper'

class FakesController < ApplicationController
include TransactionProcessing
end describe FakesController do it "should mark an item out of stock" do
item = create(:item, is_in_stock: true)
subject.process_sale(item)
expect(item.is_in_stock).to be false
end
end

And there you go! Easy, isolated tests for your controller concerns.

最新文章

  1. 自己动手写计算器v1.2
  2. PHP_解析xss攻击、sql注入
  3. python中的类变量、实例变量
  4. iOS对象序列化
  5. AngularJs $http.post 数据后台获取不到数据问题 的解决过程
  6. 2015北京网络赛 F Couple Trees 暴力倍增
  7. javaWeb中一个按钮提交两个表单
  8. Linux JDK配置
  9. 入门vue----(介绍)
  10. uptime 命令详解
  11. GZip 压缩及解压缩
  12. spring 空指针报错,Could not create connection to database server.
  13. Oarcle 入门之注释与关键字
  14. istream不是std的成员
  15. Codeforces Round #109 (Div. 1) 题解 【ABC】
  16. defer和async的详细区别
  17. WebRTC开发基础(WebRTC入门系列3:RTCDataChannel)
  18. pip virtualenv requirement
  19. 使用Docker构建AspNetCore应用
  20. Appium自动化测试-iOS

热门文章

  1. JavaScript编程总结
  2. {Reshipt}{文白}{资治通鉴}
  3. Google V8编程详解附录
  4. RHCA-红帽认证架构师
  5. 企业级监控平台开发之nagios二次开发(七)
  6. Owin SelfHost Asp.net WebApi 遇到 No type was found that matches the controller named &#39;ControllerName&#39; 异常的解决方案
  7. vc++ 判断文件或是文件夹是否存在,比较好的做法
  8. ASP.NET MVC 介绍
  9. DIOCP之工作流程图
  10. 顶点着色器详解 (Vertex Shaders)