Class: Guard::Jasmine::Runner

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/guard/jasmine/runner.rb

Overview

The Jasmine runner handles the execution of the spec through the PhantomJS binary, evaluates the JSON response from the PhantomJS Script guard_jasmine.coffee, writes the result to the console and triggers optional system notifications.

Constant Summary

THRESHOLDS =

Name of the coverage threshold options

[:statements_threshold, :functions_threshold, :branches_threshold, :lines_threshold]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

#find_free_server_port, #phantomjs_bin_valid?, #runner_available?, #which

Constructor Details

#initialize(options) ⇒ Runner

Run the supplied specs.

Parameters:

  • options (Hash)

    the options for the execution

Options Hash (options):

  • :jasmine_url (String)

    the url of the Jasmine test runner

  • :phantomjs_bin (String)

    the location of the PhantomJS binary

  • :timeout (Integer)

    the maximum time in seconds to wait for the spec runner to finish

  • :rackup_config (String)

    custom rackup config to use

  • :notification (Boolean)

    show notifications

  • :hide_success (Boolean)

    hide success message notification

  • :max_error_notify (Integer)

    maximum error notifications to show

  • :specdoc (Symbol)

    options for the specdoc output, either :always, :never

  • :console (Symbol)

    options for the console.log output, either :always, :never or :failure

  • :spec_dir (String)

    the directory with the Jasmine specs

  • :query_params (Hash)

    Parameters to pass along with the request

  • :debug (Boolean)

    display raw JSON output from the runner



38
39
40
# File 'lib/guard/jasmine/runner.rb', line 38

def initialize(options)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options



17
18
19
# File 'lib/guard/jasmine/runner.rb', line 17

def options
  @options
end

Instance Method Details

#any_coverage_threshold?Boolean (private)

Do we should check the coverage?

Returns:

  • (Boolean)

    true if any coverage threshold is set



622
623
624
# File 'lib/guard/jasmine/runner.rb', line 622

def any_coverage_threshold?
  THRESHOLDS.any? { |threshold| options[threshold] != 0 }
end

#check_coverageObject (private)

Uses the Istanbul text reported to output the result of the last coverage run.



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/guard/jasmine/runner.rb', line 385

def check_coverage
  if any_coverage_threshold?
    coverage = `#{coverage_bin} check-coverage #{ istanbul_coverage_options } #{ coverage_file } 2>&1`
    coverage = coverage.split("\n").grep(/ERROR/).join.sub('ERROR:', '')
    failed   = $? && $?.exitstatus != 0

    if failed
      Formatter.error coverage
      Formatter.notify(coverage, title: 'Code coverage failed', image: :failed, priority: 2) if options[:notification]
    else
      Formatter.success 'Code coverage succeed'
      Formatter.notify('All code is adequately covered with specs', title: 'Code coverage succeed') if options[:notification] && !options[:hide_success]
    end
  end
end

#collect_spec_errors(suites) ⇒ Array<Hash> (private)

Get all failed specs from the suites and its nested suites.

Parameters:

  • suites (Array<Hash>)

    the suites results

Returns:

  • (Array<Hash>)

    all failed



559
560
561
562
563
# File 'lib/guard/jasmine/runner.rb', line 559

def collect_spec_errors(suites)
  collect_specs(suites).map { |spec|
    (spec['errors']||[]).map { |error| format_error(error,false) }
  }.flatten
end

#collect_specs(suites) ⇒ Array<Hash> (private)

Get all specs from the suites and its nested suites.

Parameters:

  • suites (Array<Hash>)

    the suites results

Returns:

  • (Array<Hash>)

    all specs



570
571
572
573
574
575
# File 'lib/guard/jasmine/runner.rb', line 570

def collect_specs(suites)
  suites.each_with_object([]) do |suite, specs|
    specs.concat( suite['specs'] )
    specs.concat( collect_specs(suite['suites']) ) if suite['suites']
  end
end

#console_for_spec?(spec) ⇒ Boolean (private)

Are console logs shown for this spec?

Parameters:

  • spec (Hash)

    the spec

Returns:

  • (Boolean)


479
480
481
482
# File 'lib/guard/jasmine/runner.rb', line 479

def console_for_spec?(spec)
  spec['logs'] && (( spec['status'] == 'passed' && options[:console] == :always) ||
    (spec['status'] == 'failed' && options[:console] != :never) )
end

#contains_failed_spec?(suite) ⇒ Boolean (private)

Tests if the given suite has a failing spec underneath.

Parameters:

  • suite (Hash)

    the suite result

Returns:

  • (Boolean)

    the search result



549
550
551
# File 'lib/guard/jasmine/runner.rb', line 549

def contains_failed_spec?(suite)
  collect_specs([suite]).any? { |spec| spec['status'] == 'failed' }
end

#coverage_binString (private)

Returns the coverage executable path.

Returns:

  • (String)

    the path



641
642
643
# File 'lib/guard/jasmine/runner.rb', line 641

def coverage_bin
  @coverage_bin ||= which 'istanbul'
end

#coverage_fileString (private)

Get the coverage file to save all coverage data. Creates tmp/coverage if not exists.

Returns:

  • (String)

    the filename to use



650
651
652
# File 'lib/guard/jasmine/runner.rb', line 650

def coverage_file
  File.join(coverage_root, 'coverage.json')
end

#coverage_report_directoryString (private)

Creates and returns the coverage report directory.

Returns:

  • (String)

    the coverage report directory



666
667
668
# File 'lib/guard/jasmine/runner.rb', line 666

def coverage_report_directory
  File.expand_path(options[:coverage_html_dir])
end

#coverage_rootString (private)

Create and returns the coverage root directory.

Returns:

  • (String)

    the coverage root



658
659
660
# File 'lib/guard/jasmine/runner.rb', line 658

def coverage_root
  File.expand_path(File.join('tmp', 'coverage'))
end

#description_shown?(passed, spec) ⇒ Boolean (private)

Is the description shown for this spec?

Parameters:

  • passed (Boolean)

    the spec status

  • spec (Hash)

    the spec

Returns:

  • (Boolean)


498
499
500
# File 'lib/guard/jasmine/runner.rb', line 498

def description_shown?(passed, spec)
  specdoc_shown?(passed) || console_for_spec?(spec) || errors_for_spec?(spec)
end

#errors_for_spec?(spec) ⇒ Boolean (private)

Are errors shown for this spec?

Parameters:

  • spec (Hash)

    the spec

Returns:

  • (Boolean)


488
489
490
491
# File 'lib/guard/jasmine/runner.rb', line 488

def errors_for_spec?(spec)
  spec['errors'] && ((spec['status']=='passed' && options[:errors] == :always) ||
    (spec['status']=='failed' && options[:errors] != :never))
end

#evaluate_response(output, file) ⇒ Hash (private)

Evaluates the JSON response that the PhantomJS script writes to stdout. The results triggers further notification actions.

Parameters:

  • output (String)

    the JSON output the spec run

  • file (String)

    the file name of the spec

Returns:

  • (Hash)

    results of the suite's specs



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/guard/jasmine/runner.rb', line 238

def evaluate_response(output, file)
  json = output.read
  json = json.encode('UTF-8') if json.respond_to?(:encode)
  begin
    result = MultiJson.decode(json, { max_nesting: false })
    raise 'No response from Jasmine runner' if !result && options[:is_cli]
    pp result if options[:debug]
    if result['error']
      if options[:is_cli]
        raise 'An error occurred in the Jasmine runner'
      else
        notify_runtime_error(result)
      end
    elsif result
      result['file'] = file
      notify_spec_result(result)
    end

    if result && result['coverage'] && options[:coverage]
      notify_coverage_result(result['coverage'], file)
    end

    return result

  rescue MultiJson::DecodeError => e
    if e.data == ''
      if options[:is_cli]
        raise 'No response from Jasmine runner'
      else
        Formatter.error('No response from the Jasmine runner!')
      end
    else
      if options[:is_cli]
        raise "Cannot decode JSON from PhantomJS runner, message received was:\n#{json}"
      else
        Formatter.error("Cannot decode JSON from PhantomJS runner: #{ e.message }")
        Formatter.error("JSON response: #{ e.data }")
        Formatter.error("message received was:\n#{json}")
      end
    end
  ensure
    output.close
  end
end

#file_and_line_number_parts(file) ⇒ Array (private)

Splits the file name into the physical file name and the line number if present. E.g.: 'some_spec.js.coffee:10' -> ['some_spec.js.coffee', 10].

If the line number is missing the second part of the returned array is nil.

Parameters:

  • file (String)

    the spec file

Returns:

  • (Array)

    [file_name, line_number]



203
204
205
206
# File 'lib/guard/jasmine/runner.rb', line 203

def file_and_line_number_parts(file)
  match = file.match(/^(.+?)(?::(\d+))?$/)
  [match[1], match[2].nil? ? nil : match[2].to_i]
end

#format_error(error, short) ⇒ String (private)

Formats a message.

Parameters:

  • message (String)

    the error message

  • short (Boolean)

    show a short version of the message

Returns:

  • (String)

    the cleaned error message



583
584
585
586
587
588
589
590
591
# File 'lib/guard/jasmine/runner.rb', line 583

def format_error(error, short)
  message = error['message'].gsub(%r{ in http.*\(line \d+\)$},'')
  if !short && error['trace'] && error['trace'].length > 0
    location = error['trace'][0]
    "#{message} in #{location['file']}:#{location['line']}"
  else
    message
  end
end

#generate_html_reportObject (private)

Uses the Istanbul text reported to output the result of the last coverage run.



404
405
406
407
408
# File 'lib/guard/jasmine/runner.rb', line 404

def generate_html_report
  report_directory = coverage_report_directory
  `#{coverage_bin} report --dir #{ report_directory } --root #{ coverage_root } html #{ coverage_file }`
  Formatter.info "Updated HTML report available at: #{ report_directory }/index.html"
end

#generate_summary_reportObject (private)

Uses the Istanbul text-summary reporter to output the summary of all the coverage runs combined.



413
414
415
416
417
418
419
420
421
422
423
# File 'lib/guard/jasmine/runner.rb', line 413

def generate_summary_report
  Formatter.info 'Spec coverage summary:'

  puts ''

  `#{coverage_bin} report --root #{ coverage_root } text-summary #{ coverage_file }`.each_line do |line|
    puts line.sub(/\n$/, '') if line =~ /\)$/
  end

  puts ''
end

#generate_text_report(file) ⇒ Object (private)

Uses the Istanbul text reported to output the result of the last coverage run.

Parameters:

  • file (String)

    the file name of the spec



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/guard/jasmine/runner.rb', line 363

def generate_text_report(file)
  Formatter.info 'Spec coverage details:'

  if file == options[:spec_dir]
    matcher = /[|+]$/
  else
    impl    = file.sub('_spec', '').sub(options[:spec_dir], '')
    matcher = /(-+|All files|% Lines|#{ Regexp.escape(File.basename(impl)) }|#{ File.dirname(impl).sub(/^\//, '') }\/[^\/])/
  end

  puts ''

  `#{coverage_bin} report --root #{ coverage_root } text #{ coverage_file }`.each_line do |line|
    puts line.sub(/\n$/, '') if line =~ matcher
  end

  puts ''
end

#indent(message, level) ⇒ Object (private)

Indent a message.

Parameters:

  • message (String)

    the message

  • level (Number)

    the indention level



539
540
541
# File 'lib/guard/jasmine/runner.rb', line 539

def indent(message, level)
  (' ' * level) + message
end

#istanbul_coverage_optionsString (private)

Converts the options to Istanbul recognized options

Returns:

  • (String)

    the command line options



630
631
632
633
634
635
# File 'lib/guard/jasmine/runner.rb', line 630

def istanbul_coverage_options
  THRESHOLDS.inject([]) do |coverage, name|
    threshold = options[name]
    coverage << (threshold != 0 ? "--#{ name.to_s.sub('_threshold', '') } #{ threshold }" : '')
  end.reject(&:empty?).join(' ')
end

#it_and_describe_lines(file, from, to) ⇒ Object (private)

Returns all lines of the file that are either a 'describe' or a 'it' declaration.

Parameters:

  • file (String)

    the spec file

  • from (Numeric)

    the first line in the range

  • to (Numeric)

    the last line in the range



216
217
218
219
# File 'lib/guard/jasmine/runner.rb', line 216

def it_and_describe_lines(file, from, to)
  File.readlines(file)[from, to].
    select { |x| x =~ /^\s*(it|describe)/ }
end

#jasmine_suite(file) ⇒ String (private)

Get the Jasmine test runner URL with the appended suite name that acts as the spec filter.

Parameters:

  • file (String)

    the spec file

Returns:

  • (String)

    the Jasmine url



121
122
123
# File 'lib/guard/jasmine/runner.rb', line 121

def jasmine_suite(file)
  options[:jasmine_url] + query_string_for_suite(file)
end

#notify_coverage_result(coverage, file) ⇒ Object (private)

Notification about the coverage of a spec run, success or failed, and some stats.

Parameters:

  • coverage (Hash)

    the coverage hash from the JSON

  • file (String)

    the file name of the spec



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/guard/jasmine/runner.rb', line 336

def notify_coverage_result(coverage, file)
  if coverage_bin
    FileUtils.mkdir_p(coverage_root) unless File.exist?(coverage_root)

    update_coverage(coverage, file)

    if options[:coverage_summary]
      generate_summary_report
    else
      generate_text_report(file)
    end

    check_coverage

    if options[:coverage_html]
      generate_html_report
    end
  else
    Formatter.error('Skipping coverage report: unable to locate istanbul in your PATH')
  end
end

#notify_runtime_error(result) ⇒ Object (private)

Notification when a system error happens that prohibits the execution of the Jasmine spec.

Parameters:

  • result (Hash)

    the suite result



288
289
290
291
292
293
# File 'lib/guard/jasmine/runner.rb', line 288

def notify_runtime_error(result)
  message = "An error occurred: #{ result['error'] }"
  Formatter.error(message )
  Formatter.error( result['trace'] ) if result['trace']
  Formatter.notify(message, title: 'Jasmine error', image: :failed, priority: 2) if options[:notification]
end

#notify_spec_result(result) ⇒ Object (private)

Notification about a spec run, success or failure, and some stats.

Parameters:

  • result (Hash)

    the suite result



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/guard/jasmine/runner.rb', line 300

def notify_spec_result(result)
  specs         = result['stats']['specs'] - result['stats']['disabled']
  failed        = result['stats']['failed']
  time          = sprintf( '%0.2f', result['stats']['time'] )
  specs_plural  = specs == 1 ? '' : 's'
  failed_plural = failed == 1 ? '' : 's'
  Formatter.info("Finished in #{ time } seconds")
  pending = result['stats']['pending'].to_i > 0 ? " #{result['stats']['pending']} pending," : ""
  message      = "#{ specs } spec#{ specs_plural },#{pending} #{ failed } failure#{ failed_plural }"
  full_message = "#{ message }\nin #{ time } seconds"
  passed       = failed == 0

  report_specdoc(result, passed) if specdoc_shown?(passed)

  if passed
    Formatter.success(message)
    Formatter.notify(full_message, title: 'Jasmine suite passed') if options[:notification] && !options[:hide_success]
  else
    errors = collect_spec_errors(result['suites'])
    error_message = errors[0..options[:max_error_notify]].join("\n")

    Formatter.error(message)
    if options[:notification]
      Formatter.notify( "#{error_message}\n#{full_message}",
        title: 'Jasmine suite failed', image: :failed, priority: 2)
    end
  end

end

#notify_start_message(paths) ⇒ Object (private)

Parameters:

  • paths (Array<String>)

    the spec files or directories



75
76
77
78
79
80
81
82
83
# File 'lib/guard/jasmine/runner.rb', line 75

def notify_start_message(paths)
  message = if paths == [options[:spec_dir]]
              'Run all Jasmine suites'
            else
              "Run Jasmine suite#{ paths.size == 1 ? '' : 's' } #{ paths.join(' ') }"
            end

  Formatter.info(message, reset: true)
end

#phantomjs_commandString (private)

Get the PhantomJS binary and script to execute.

Returns:

  • (String)

    the command



110
111
112
113
# File 'lib/guard/jasmine/runner.rb', line 110

def phantomjs_command
  options[:phantomjs_bin] + ' ' + phantomjs_script
  #options[:phantomjs_bin] + ' --remote-debugger-port=9000 ' + phantomjs_script
end

#phantomjs_scriptString (private)

Get the PhantomJS script that executes the spec and extracts the result from the headless DOM.

Returns:

  • (String)

    the path to the PhantomJS script



130
131
132
# File 'lib/guard/jasmine/runner.rb', line 130

def phantomjs_script
  File.expand_path(File.join(File.dirname(__FILE__), 'phantomjs', 'guard-jasmine.js'))
end

#query_string_for_suite(file) ⇒ String (private)

The suite name must be extracted from the spec that will be run.

Parameters:

  • file (String)

    the spec file

Returns:

  • (String)

    the suite name



140
141
142
143
144
145
146
147
148
149
# File 'lib/guard/jasmine/runner.rb', line 140

def query_string_for_suite(file)
  params = {}
  if options[:query_params]
    params.merge!(options[:query_params])
  end
  if file != options[:spec_dir]
    params[:spec] = suite_from_line_number(file) || suite_from_first_describe(file)
  end
  params.empty? ? "" : "?"+URI.encode_www_form(params)
end

#report_specdoc(result, passed) ⇒ Object (private)

Specdoc like formatting of the result.

Parameters:

  • result (Hash)

    the suite result

  • passed (Boolean)

    status



430
431
432
433
434
# File 'lib/guard/jasmine/runner.rb', line 430

def report_specdoc(result, passed)
  result['suites'].each do |suite|
    report_specdoc_suite(suite, passed)
  end
end

#report_specdoc_errors(spec, level) ⇒ Object (private)

Shows the errors for a given spec.

Parameters:

  • spec (Hash)

    the spec result

  • level (Number)

    the indention level



521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/guard/jasmine/runner.rb', line 521

def report_specdoc_errors(spec, level)
  if spec['errors'] && (options[:errors] == :always || (options[:errors] == :failure && spec['status']=='failed'))
    spec['errors'].each do |error|
      Formatter.spec_failed(indent("#{ format_error(error,true)  }", level))
      if error['trace']
        error['trace'].each do |trace|
          Formatter.spec_failed(indent("#{ trace['file'] } on line #{ trace['line'] }", level+2))
        end
      end
    end
  end
end

#report_specdoc_logs(spec, level) ⇒ Object (private)

Shows the logs for a given spec.

Parameters:

  • spec (Hash)

    the spec result

  • level (Number)

    the indention level



507
508
509
510
511
512
513
514
# File 'lib/guard/jasmine/runner.rb', line 507

def report_specdoc_logs(spec, level)
  if console_for_spec?(spec)
    spec['logs'].each do |log_level, message|
      log_level = log_level == 'log' ? '' : "#{log_level.upcase}: "
      Formatter.info(indent("#{log_level}#{ message }", level))
    end
  end
end

#report_specdoc_suite(suite, run_passed, level = 0) ⇒ Object (private)

Show the suite result.

Parameters:

  • suite (Hash)

    the suite

  • passed (Boolean)

    status

  • level (Number) (defaults to: 0)

    the indention level



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/guard/jasmine/runner.rb', line 442

def report_specdoc_suite(suite, run_passed, level = 0)

 # Print the suite description when the specdoc is shown or there are logs to display
  Formatter.suite_name((' ' * level) + suite['description'])

  suite['specs'].each do |spec|
    # Specs are shown if they failed, or if they passed and the "focus" option is falsey
    # If specs are going to be shown, then pending are also shown
    # If the focus option is set, then only failing tests are shown
    next unless :always==options[:specdoc] || spec['status'] == 'failed' || ( !run_passed && !options[:focus] )
    if spec['status'] == 'passed'
      Formatter.success(indent("#{ spec['description'] }", level))
    elsif spec['status'] == 'failed'
      Formatter.spec_failed(indent("#{ spec['description'] }", level))
    else
      Formatter.spec_pending(indent("#{ spec['description'] }", level))
    end
    report_specdoc_errors(spec, level)
    report_specdoc_logs(spec, level)
  end

  suite['suites'].each { |s| report_specdoc_suite(s, run_passed, level + 2) } if suite['suites']
end

#run(paths, per_run_options = {}) ⇒ Hash<String,Array>

Returns keys for the spec_file, value is array of failure messages. Only specs with failures will be returned. Therefore an empty? return hash indicates success.

Parameters:

  • paths (Array<String>)

    the spec files or directories

Returns:

  • (Hash<String,Array>)

    keys for the spec_file, value is array of failure messages. Only specs with failures will be returned. Therefore an empty? return hash indicates success.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/guard/jasmine/runner.rb', line 45

def run(paths, per_run_options = {})
  previous_options = @options
  @options.merge!( per_run_options )

  return {} if paths.empty?

  notify_start_message(paths)

  run_results = paths.each_with_object({}) do |file, results|
    if File.exist?(file_and_line_number_parts(file)[0])
      results[file] = evaluate_response(run_jasmine_spec(file), file)
    end
  end
  # return the errors
  return run_results.each_with_object({}) do | spec_run, hash |
    file, r = spec_run
    errors = collect_spec_errors(r['suites']||[])
    errors.push( r['error'] ) if r.has_key? 'error'
    hash[file] = errors unless errors.empty?
  end
ensure
  @options=previous_options
end

#run_jasmine_spec(file) ⇒ Object (private)

Run the Jasmine spec by executing the PhantomJS script.

Parameters:

  • file (String)

    the path of the spec



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/guard/jasmine/runner.rb', line 89

def run_jasmine_spec(file)
  suite = jasmine_suite(file)

  arguments = [
    options[:timeout] * 1000,
    options[:specdoc],
    options[:focus],
    options[:console],
    options[:errors],
    options[:junit],
    options[:junit_consolidate],
    "'#{ options[:junit_save_path] }'"
  ]
  cmd = "#{ phantomjs_command } \"#{ suite }\" #{ arguments.collect { |i| i.to_s }.join(' ')}"
  IO.popen(cmd, 'r:UTF-8')
end

#spec_title(line) ⇒ String (private)

Extracts the title of a 'description' or a 'it' declaration.

Parameters:

  • the (String)

    line content

Returns:

  • (String)

    the extracted title



226
227
228
# File 'lib/guard/jasmine/runner.rb', line 226

def spec_title(line)
  line[/['"](.+?)["']/, 1]
end

#specdoc_shown?(passed) ⇒ Boolean (private)

Is the specdoc shown for this suite?

Parameters:

  • passed (Boolean)

    the spec status

Returns:

  • (Boolean)


470
471
472
# File 'lib/guard/jasmine/runner.rb', line 470

def specdoc_shown?(passed)
  options[:specdoc] == :always || (options[:specdoc] == :failure && !passed)
end

#suite_from_first_describe(file) ⇒ String (private)

The suite name must be extracted from the spec that will be run. This is done by parsing from the head of the spec file until the first describe function is found.

Parameters:

  • file (String)

    the spec file

Returns:

  • (String)

    the suite name



185
186
187
188
189
190
191
# File 'lib/guard/jasmine/runner.rb', line 185

def suite_from_first_describe(file)
  File.foreach(file) do |line|
    if line =~ /describe\s*[("']+(.*?)["')]+/ #'
      return $1
    end
  end
end

#suite_from_line_number(file) ⇒ String (private)

When providing a line number by either the option or by a number directly after the file name the suite is extracted fromt the corresponding line number in the file.

Parameters:

  • file (String)

    the spec file

Returns:

  • (String)

    the suite name



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/guard/jasmine/runner.rb', line 158

def suite_from_line_number(file)
  file_name, line_number = file_and_line_number_parts(file)
  line_number ||= options[:line_number]

  if line_number
    lines = it_and_describe_lines(file_name, 0, line_number)
    last = lines.pop

    last_indentation = last[/^\s*/].length
    # keep only lines with lower indentation
    lines.delete_if { |x| x[/^\s*/].length >= last_indentation }
    # remove all 'it'
    lines.delete_if { |x| x =~ /^\s*it/ }

    lines << last
    lines.map { |x| spec_title(x) }.join(' ')
  end
end

#update_coverage(coverage, file) ⇒ Object (private)

Updates the coverage data with new data for the implementation file. It replaces the coverage data if the file is the spec dir.

Parameters:

  • coverage (Hash)

    the last run coverage data

  • file (String)

    the file name of the spec



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/guard/jasmine/runner.rb', line 599

def update_coverage(coverage, file)
  if file == options[:spec_dir]
    File.write(coverage_file, MultiJson.encode(coverage, { max_nesting: false }))
  else
    if File.exist?(coverage_file)
      impl     = file.sub('_spec', '').sub(options[:spec_dir], '')
      coverage = MultiJson.decode(File.read(coverage_file), { max_nesting: false })

      coverage.each do |coverage_file, data|
        coverage[coverage_file] = data if coverage_file == impl
      end

      File.write(coverage_file, MultiJson.encode(coverage, { max_nesting: false }))
    else
      File.write(coverage_file, MultiJson.encode({ }))
    end
  end
end