Rails Minitest style 指南

In the test,  we should use the ‘describe’,  ‘context’, ‘it’ structure.

Here I use a controller test as an example.

I have this my_controller.rb with two controller actions:

class MyController < ApplicationController
  def controller_action_1
  # Code goes here
  end

  def controller_action_2
  # Code goes here
  end
end

And controller test file my_controller_test.rb:

require ‘test_helper’

class MyControllerTest < ActionController::TestCase
  # Initialize the variables that will be used in all describe block tests within MyControllerTest class
  before do
    v_block = ‘this variable is only accessible in this block’
    @v_describe_level = ‘this varible is accessible in all describe blocks’
  end

  # Test for controller action 1
  describe ‘#controller_action_1′ do
    # Intialize the variables that will be used in all context block tests within this describe block
    before do
      v_block = ‘this variable is only accessible in this block’
      @v_context_level = ‘this varible is accessible in all context blocks’
    end

    context ‘when the user is admin’ do
      # Intialize the variables that will be used in all it block tests within this context block
      before do
        v_block = ‘this variable is only accessible in this block’
        @v_it_level = ‘this varible is accessible in all it blocks’
      end

      it ‘must has admin role’ do
        # Code goes here. Examples: http://ruby-doc.org/stdlib-1.9.3/libdoc/minitest/spec/rdoc/MiniTest/Expectations.html
        # must_be
        # must_be_empty
        # must_be_nil
        # must_be_same_as
        # must_equal
        # must_raise
        # wont_be
        # wont_be_nil
        # wont_equal
        # wont_include
      end

      it ‘must redirect to admin management page’ do
        # Code goes here, example:
        # assert_redirected_to
      end
    end

    context ‘when the user is not admin’ do
      it ‘must not have admin role’ do
      end

      it ‘must redirect to non-admin management page’ do
      end
    end
  end

  describe ‘#controller_action_2′ do
    # Code goes here
  end

  private

  # Helper functions goes here
end


Some reminder:

1. Given, When, Then

2. Use fixture instead of creating data on the go

3. If no Before block, don't need to use context


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值