Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/cucumber/glue/snippet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def typed_pattern
def to_s
header = generated_expressions.each_with_index.map do |expr, i|
prefix = i.zero? ? '' : '# '
"#{prefix}#{code_keyword}('#{expr.source}') do#{parameters(expr)}"
"#{prefix}#{code_keyword}(#{quoted_expression_source(expr)}) do#{parameters(expr)}"
end.join("\n")

body = <<~DOC.chomp
Expand All @@ -108,6 +108,15 @@ def parameters(expr)
parameter_names.empty? ? '' : " |#{parameter_names.join(', ')}|"
end

def quoted_expression_source(expr)
source = expr.source

return "'#{source.gsub(/\\/) { |char| "\\#{char}" }}'" unless source.include?("'")

escaped_source = source.gsub(/["\\#]/) { |char| "\\#{char}" }
"\"#{escaped_source}\""
end

def self.description
'Cucumber Expressions'
end
Expand Down
33 changes: 33 additions & 0 deletions spec/cucumber/glue/snippet_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,39 @@ module Glue

expect(snippet.to_s).to eq(cucumber_output)
end

it 'uses double quotes for generated cucumber expression snippets with apostrophes' do

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These aren't cucumber expression snippets. They're all regular snippets

@StantonMatt StantonMatt Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right; I renamed those examples in 06591c7 so they refer to generated snippets rather than cucumber expression snippets.

@step_text = "Lucy hears Sean's message"
cucumber_output = <<~CUKE.chomp
Given("Lucy hears Sean's message") do
pending # Write code here that turns the phrase above into concrete actions
end
CUKE

expect(snippet.to_s).to eq(cucumber_output)
end

it 'escapes backslashes in single quoted cucumber expression snippets' do
@step_text = 'Lucy hears trailing \\'
cucumber_output = <<~'CUKE'.chomp
Given('Lucy hears trailing \\') do
pending # Write code here that turns the phrase above into concrete actions
end
CUKE

expect(snippet.to_s).to eq(cucumber_output)
end

it 'escapes interpolation markers in double quoted cucumber expression snippets' do
@step_text = 'Lucy hears Sean\'s #@message'
cucumber_output = <<~'CUKE'.chomp
Given("Lucy hears Sean's \#@message") do
pending # Write code here that turns the phrase above into concrete actions
end
CUKE

expect(snippet.to_s).to eq(cucumber_output)
end
end
end
end
Expand Down
Loading