Skip to content

Commit 0241b77

Browse files
adbatistamattwynne
authored andcommitted
add diff! method to DataTable
1 parent 9df4382 commit 0241b77

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed

features/docs/defining_steps/table_diffing.feature

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ Feature: Table diffing
3333
| x | y |
3434
| a | b |
3535
| a | c |
36-
Tables were not identical (Cucumber::Ast::Table::Different)
36+
Tables were not identical (Cucumber::MultilineArgument::DataTable::Different)
3737
./features/step_definitions/steps.rb:2:in `/the table should be:/'
3838
features/tables.feature:3:in `Then the table should be:'
3939

lib/cucumber/multiline_argument.rb

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,70 @@ def append_to(array)
3737
def to_json(options)
3838
raw.to_json(options)
3939
end
40+
41+
def diff!(other_table)
42+
other_table = ensure_table(other_table)
43+
other_table_cell_matrix = other_table.cell_matrix
44+
45+
ensure_green!
46+
47+
require_diff_lcs
48+
cell_matrix.extend(Diff::LCS)
49+
50+
changes = cell_matrix.diff(other_table_cell_matrix).flatten
51+
52+
return if changes.empty?
53+
54+
inserted = 0
55+
missing = 0
56+
57+
changes.each do |change|
58+
if(change.action == '-')
59+
missing_row_pos = change.position + inserted
60+
cell_matrix[missing_row_pos].each{|cell| cell.status = :undefined}
61+
62+
missing += 1
63+
else # '+'
64+
inserted_row = change.element
65+
inserted_row.each{|cell| cell.status = :comment}
66+
67+
insert_row_pos = change.position + missing
68+
cell_matrix.insert(insert_row_pos, inserted_row)
69+
70+
inserted += 1
71+
end
72+
end
73+
74+
raise Different.new(self)
75+
end
76+
77+
def ensure_green! #:nodoc:
78+
each_cell{|cell| cell.status = :passed}
79+
end
80+
81+
private
82+
83+
def ensure_table(table_or_array) #:nodoc:
84+
return table_or_array if DataTable === table_or_array
85+
DataTable.new(table_or_array)
86+
end
87+
88+
def require_diff_lcs #:nodoc:
89+
begin
90+
require 'diff/lcs'
91+
rescue LoadError => e
92+
e.message << "\n Please gem install diff-lcs\n"
93+
raise e
94+
end
95+
end
96+
97+
class Different < StandardError
98+
attr_reader :table
99+
def initialize(table)
100+
@table = table
101+
super("Tables were not identical")
102+
end
103+
end
40104
end
41105

42106
class None
@@ -46,7 +110,6 @@ def append_to(array)
46110
def describe_to(visitor)
47111
end
48112
end
49-
50113
end
51114
end
52115

0 commit comments

Comments
 (0)