RSpec basics
Recently I have re-studied the RSpec. This is just my reminder.
- describe
- to be used to group something to be described. can be nested.
- context
- same as describe but usually used to list some different conditions
- it
- to be used to write test case. If it's a test for models or controller, it should have only one expectation.
- expect
- to be used to describe an expectation. Several operators(to, not_to, etc) and matchers(be, eq, etc.) are available.
- subject
- to be used to declare a test object which can be used implicitly after here - the following its sentence uses this to check the description method.
An easy example is below:
class Computer attr_accessor :cpu, :memory, :disk, :has_too_big_cpu def initialize(cpu, memory, disk) raise 'Non integer values given' unless cpu.is_a? Integer and memory.is_a? Integer and disk.is_a? Integer @cpu = cpu @memory = memory @disk = disk @has_too_big_cpu = true if cpu > 10 end def description return "CPU: #{@cpu}, Memory: #{@memoory}, Disk: #{@disk}"; end end describe 'Computer' do describe 'initialization' do context 'with non-integer values' do it 'will raise an exception' do expect { Computer.new(1, 1, '10GB') }.to raise_error 'Non integer values given' end end context 'with too big CPU' do it 'will set has_too_big_cpu' do computer = Computer.new(15, 1, 1) expect(computer.has_too_big_cpu).to be true end end end subject { Computer.new(1, 1, 10) } its(:description) { should eq "CPU: 1, Memory: , Disk: 10" } end