Created
March 17, 2015 10:12
-
-
Save holysugar/f36f4e13fbbe3e8f10f7 to your computer and use it in GitHub Desktop.
assert_change 試作版
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'test/unit/assertions' | |
| module AssertChange | |
| # fixme message? | |
| def assert_change(value_proc, options = {}, &event_proc) | |
| change = Change.new(value_proc) | |
| change.perform(event_proc) | |
| case | |
| when options[:by] | |
| change.assert_change_by(options[:by]) | |
| when options[:from], options[:to] | |
| change.assert_change_from_to(from: options[:from], to: options[:to]) | |
| else | |
| change.assert_change | |
| end | |
| end | |
| def assert_not_change(value_proc, options = {}, &event_proc) | |
| change = Change.new(value_proc) | |
| change.perform(event_proc) | |
| change.assert_not_change | |
| end | |
| class Change | |
| include Test::Unit::Assertions | |
| attr_reader :actual_before, :actual_after | |
| def initialize(value_proc, message = nil) | |
| @value_proc = value_proc | |
| @message = message | |
| end | |
| def perform(event_proc) | |
| @actual_before = evaluate_value_block | |
| event_proc.call | |
| @actual_after = evaluate_value_block | |
| end | |
| def assert_change_by(by) | |
| assert { by == @actual_after - @actual_before } | |
| end | |
| def assert_change_from_to(from: nil, to: nil) | |
| assert_equal from, actual_before, "expect to change from #{from} but actual #{actual_before}" if from | |
| assert_equal to, actual_after, "expect to change to #{to} but actual #{actual_after}" if to | |
| end | |
| def assert_change | |
| assert_not_equal @actual_before, @actual_after, "expect to change #{@actual_before} but not change (actual: #{@actual_after})" | |
| end | |
| def assert_not_change | |
| assert_equal @actual_before, @actual_after, "expect not to change #{@actual_before} but changed (actual: #{@actual_after})" | |
| end | |
| private | |
| def evaluate_value_block | |
| val = @value_proc.call | |
| case val | |
| when IO | |
| val | |
| when Enumerable, String | |
| val.dup | |
| else | |
| val | |
| end | |
| end | |
| end | |
| private | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment