Skip to content
Browse files

small performance optimization of assert_same_elements

prevent re-counting the number of occurrences there are in arrays for duplicated values
  • Loading branch information...
1 parent 10f0a7e commit a53799ca251fd18abde474842841ee2d322bed90 @misfo misfo committed Jan 27, 2011
Showing with 9 additions and 2 deletions.
  1. +2 −2 lib/shoulda/context/assertions.rb
  2. +7 −0 test/shoulda/helpers_test.rb
View
4 lib/shoulda/context/assertions.rb
@@ -9,8 +9,8 @@ def assert_same_elements(a1, a2, msg = nil)
[a1, a2].each {|a| assert_respond_to(a, m, "Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.") }
end
- assert a1h = a1.inject({}) { |h,e| h[e] = a1.select { |i| i == e }.size; h }
- assert a2h = a2.inject({}) { |h,e| h[e] = a2.select { |i| i == e }.size; h }
+ assert a1h = a1.inject({}) { |h,e| h[e] ||= a1.select { |i| i == e }.size; h }
+ assert a2h = a2.inject({}) { |h,e| h[e] ||= a2.select { |i| i == e }.size; h }
assert_equal(a1h, a2h, msg)
end
View
7 test/shoulda/helpers_test.rb
@@ -26,10 +26,17 @@ class HelpersTest < Test::Unit::TestCase # :nodoc:
assert_raises(Test::Unit::AssertionFailedError) do
assert_same_elements(@a, [3, 3, "def", "abc"])
end
+ assert_same_elements([@a, "abc"].flatten, ["abc", 3, "def", "abc"])
assert_raises(Test::Unit::AssertionFailedError) do
assert_same_elements([@a, "abc"].flatten, [3, 3, "def", "abc"])
end
end
+
+ should "only count the number of occurrences once for each unique value" do
+ a1 = [@a, "abc"].flatten
+ a1.expects(:select).times(3).returns(["abc", "abc"], ["def"], [3])
+ assert_same_elements(a1, ["abc", 3, "def", "abc"])
+ end
end
context "a matching matcher" do

0 comments on commit a53799c

Please sign in to comment.
Something went wrong with that request. Please try again.