Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active February 6, 2017 15:40
Show Gist options
  • Save JoshCheek/4632048 to your computer and use it in GitHub Desktop.
Save JoshCheek/4632048 to your computer and use it in GitHub Desktop.
RSpec crash course.
  • specs go in the "spec" directory
  • specs end in "_spec.rb"
  • toplevel begins with describe
  • inside of a describe you have an it
  • example is an alias for it
  • inside of it blocks, you write your code and assertions
  • run with $ rspec or $ rspec spec/some_spec.rb
  • if you need common setup (e.g. add another dir to the load path), put into "spec/spec_helper.rb" and then `require "spec_helper" at the top of the spec
  • using let will allow you to name a value that you want to call from your spec, it will only be calculated once per spec. It will not be called until you invoke it.
  • before will run before each spec, you can set variables / establish state (e.g. put values into a db)
  • describes can be nested inside of each other.
class Divider
def self.div2(n)
n / 2
end
end
require 'spec_helper'
describe "my example" do
it "passes" do
1.should == 1
end
it "fails" do
1.should == 2
end
example "times2" do
Multiplier.times2(3).should == 6
end
example "div2" do
Divider.div2(6).should == 3
end
before do
@num1 = 5
end
let(:num2) { 10 }
# this is approximately the same as
# def num2
# @num2 ||= 10
# end
example "using before and let blocks" do
Multiplier.times2(@num1).should == num2
end
describe 'nested' do
it 'works in here too' do
true.should == true
end
end
end
class Multiplier
def self.times2(n)
n * 2
end
end
require 'multiplier'
$LOAD_PATH.unshift(File.expand_path('../../lib2', __FILE__))
require 'divider'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment