zoukankan      html  css  js  c++  java
  • How to Test Controller Concerns in Rails 4

    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.

  • 相关阅读:
    Guid ToString 格式
    SQL Server 自增字段归零
    一些被触动的话
    【简易教程】在网站上养一只萌咔咔的小仓鼠
    SQL分页语句
    WPF使用System.Windows.SystemParameters类获得屏幕分辨率
    WPF编程学习——窗口
    C# .net WPF无边框移动窗体
    WPF 4 Ribbon 开发 之 快捷工具栏(Quick Access Toolbar)
    转 遗传算法简介
  • 原文地址:https://www.cnblogs.com/goody9807/p/5481345.html
Copyright © 2011-2022 走看看