Installing rspec is easy when you have rubygems
installed:
NOTE: you may need to use sudo
for installation of gems
gem install --no-ri --no-rdoc rspec
Now lets create a file called math_spec.rb
:
describe "math operations" do
it "addition works properly" do
expect(4 + 4).to eq(8)
end
end
And run the spec:
rspec math_spec.rb --color --format doc
Now lets create a file called example_spec.rb
:
describe "#example" do
it "should have contain certain elements" do
expect(1..5).to include(3)
end
it "has a method called to_a" do
expect(1..2).to respond_to("to_a")
end
it "somebody should end with body with string" do
expect("somebody").to match("body")
end
it "somebody should end with body with regex" do
expect("somebody").to match(/^.*body$/)
end
end
To run in:
$ rspec example_spec.rb
Check out the other matchers here
Now lets write some advanced matchers. Create a file called advanced_spec.rb
:
describe "#advanced" do
it "should have contain certain exact elements" do
expect(1..5).to contain_exactly(1, 2, 3, 4, 5)
end
it "should have contain certain exact matching elements" do
expect(["somebody", 3]).to contain_exactly(
a_string_starting_with("some"),
a_value_between(1, 5)
)
end
it "should start and end with expected values" do
expect((1..5).to_a).to start_with(1).and end_with(5)
end
it "random should be random" do
(1..10).to_a.each do
expect(rand(3)).to eq(0).or eq(1).or eq(2)
expect(rand(3)).to_not eq(3)
end
end
end
$ rspec advanced_spec.rb
NOTE: you may run across the old syntax:
describe "foo" do
it "should do stuff" do
"somebody".should match("body")
end
end
To run both styles, you may need some configuration here