Ruby rspec
From wikinotes
rspec is a testing framework for ruby.
It grew out of behaviour-driven-development.
rspec naming conventions deviate from the norm.
Documentation
official docs https://rspec.info/documentation/
Install
gem install rspec
Example
cd yourproject rspec --init # create new testproject# spec/lib/mymodule_spec.rb require "rspec" describe MyClass do # tests for 'MyClass' # it defines a test it "is named Foo" # name of test myclass = MyClass.new # ...contents... myclass.name.should == 'Foo' end # xit defines a pending test # (does not show false, shows pending) xit "is truthy" end# lib/mymodule.rb class MyClass attr_accessor :name def initialize @name = 'Foo' end end
Syntax
subject/described_class
If an object is passed to
describe
, it does not need to be instantiated, and is available magically with keywordsubject
.describe MyClass it 'returns true' do subject.val.should eq(true) end endAlternatively, you can refer to the described class as described_class.
describe MyClass it 'is over 9000' do instance = described_class.new(rating: 9001) expect(instance.rating).to > 9000 end endmethod tests
describe MyClass # tests on instance methods describe '#instance_method' it 'returns true' do # .. end end # tests on class methods describe '.class_method' it 'returns true' do # .. end end endcontext
context is simply a way of grouping tests under a label when a particular condition is true.
describe Dog context 'when age > 10' do it 'is sleepy after two hours' do dog = Dog.new(age: 15) expect(dog).to be_sleepy end end context 'when age < 2' it 'is not sleepy before 10 hours' do dog = Dog.new(age: 1) expect(dog).not_to be_sleepy end end end