Skip to content

Instantly share code, notes, and snippets.

@niku
Created March 15, 2011 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niku/870897 to your computer and use it in GitHub Desktop.
Save niku/870897 to your computer and use it in GitHub Desktop.
How do I use expect{}.to change().from().to() on Array?
require 'rspec'
class Int
attr_reader :count
def initialize
@count = 0
end
def increment
@count += 1
end
end
class Ary
attr_reader :ary
def initialize
@count = 0
@ary = []
end
def increment
@ary << @count
@count += 1
end
end
describe Int, "#increment" do
subject{ Int.new }
it "should increment the count" do
expect { subject.increment }.to change(subject, :count).from(0).to(1)
end
it "should increment the count by 1" do
expect { subject.increment }.to change(subject, :count).by(1)
end
end
describe Ary, "#ary" do
subject{ Ary.new }
it "should increment the ary" do
expect { subject.increment }.to change(subject, :ary).from([0]).to([0,1])
end
it "should increment the ary by [1]" do
expect { subject.increment }.to change(subject, :ary).by([1])
end
end
# /Users/niku% ruby -v
# ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0]
# /Users/niku% rspec --version
# 2.5.1
# /Users/niku% rspec --color --format documentation expect_spec.rb
#
# Int#increment
# should increment the count
# should increment the count by 1
#
# Ary#ary
# should increment the ary (FAILED - 1)
# should increment the ary by [1] (FAILED - 2)
#
# Failures:
#
# 1) Ary#ary should increment the ary
# Failure/Error: expect { subject.increment }.to change(subject, :ary).from([0]).to([0,1])
# ary should have been changed to [0, 1], but is now [0]
# # ./expect_spec.rb:39:in `block (2 levels) in <top (required)>'
#
# 2) Ary#ary should increment the ary by [1]
# Failure/Error: expect { subject.increment }.to change(subject, :ary).by([1])
# ary should have been changed by [1], but was changed by []
# # ./expect_spec.rb:43:in `block (2 levels) in <top (required)>'
#
# Finished in 0.00117 seconds
# 4 examples, 2 failures
require 'rspec'
class Ary
attr_reader :ary
def initialize
@count = 0
@ary = []
increment
end
def increment
@ary << @count
@count += 1
end
end
describe Ary, "#ary" do
subject{ Ary.new }
it "should increment the ary" do
expect { subject.increment }.to change{ subject.ary.clone }.from([0]).to([0,1])
end
it "should increment the ary by [1]" do
expect { subject.increment }.to change{ subject.ary.clone }.by([1])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment