Top Level Namespace

Defined Under Namespace

Modules: ActionDispatch, ActiveSupport, Admin, AdminGate, Cybertrain, Gen, I18n, ViewComponent Classes: Article, ArticleRelation, Comment, CommentComponent, CommentRelation, CybertrainJobsController, Date, Integer, Time, WelcomeJob

Instance Method Summary collapse

Instance Method Details

#assert(condition, message = "expected condition to be truthy")

This method returns an undefined value.

Passes when the condition is truthy.

Parameters:

  • condition (Object)
  • message (String) (defaults to: "expected condition to be truthy") —

    the failure message



659
660
661
662
# File 'cybertrain/test.rb', line 659

def assert(condition, message = "expected condition to be truthy")
  Cybertrain::Test.count_assertion
  flunk(message) unless condition
end

#assert_broadcasts(stream, count) { ... } ⇒ Array<String>

Passes when count messages were broadcast to stream (rows written to cybertrain_messages) while the block ran, or, without a block, since the test began; answers their payloads, oldest first. stream is a name or a record (its Cybertrain::Stream.name_for, "articles:12").

Only rows still in the table are counted. In-process nothing deletes them, but a test that boots a real server (Application#serve) runs its poller, which prunes rows older than Config#stream_retention by the Clock: after travel_to far ahead, rows broadcast before the travel can be gone, so a count without a block comes out low and assert_no_broadcasts passes. Count before travelling, or wrap the broadcasting code in the block.

Examples:

payloads = assert_broadcasts(articles(:one), 1) do
  post article_comments_path(articles(:one)), params: { comment: { body: "Hi" } }
end
assert_includes payloads[0], 'target="comments"'

Parameters:

Yields:

  • the code that broadcasts (optional)

Returns:

  • (Array<String>) —

    the payloads counted

Raises:

  • (ArgumentError) —

    for a record that is not saved



347
348
349
350
351
352
353
354
355
356
357
# File 'cybertrain/test/broadcasts.rb', line 347

def assert_broadcasts(stream, count)
  name = Cybertrain::Stream.name_for(stream)
  floor = Cybertrain::Test.case_message_floor
  if block_given?
    floor = Cybertrain::Test::Broadcasts.head_id
    yield
  end
  payloads = Cybertrain::Test::Broadcasts.payloads_after(name, floor)
  Cybertrain::Test.check_broadcasts(name, count, payloads.length)
  payloads
end

#assert_changes(expression, from: Cybertrain::Test::UNSET, to: Cybertrain::Test::UNSET) { ... } ⇒ nil

Passes when the block changes the value of expression (compared with ==), from from: and to to: when they are given (to: nil is an expectation). Checked in Rails’ order: from:, then the change, then to:.

Examples:

assert_changes(-> { article.reload.title }, from: "a", to: "b") do
  patch article_path(article), params: { article: { title: "b" } }
end

Parameters:

  • expression (Proc) —

    a lambda

  • from (Object) (defaults to: Cybertrain::Test::UNSET) —

    the value before

  • to (Object) (defaults to: Cybertrain::Test::UNSET) —

    the value after

Yields:

  • the code that makes the change

Returns:

  • (nil) —

    not the block’s value, as in Rails: one return type per method name (spikes/NOTES.md rules 10, 34)



470
471
472
473
474
475
# File 'cybertrain/test/assertions.rb', line 470

def assert_changes(expression, from: Cybertrain::Test::UNSET, to: Cybertrain::Test::UNSET)
  before = expression.call
  yield
  after = expression.call
  Cybertrain::Test.check_changes(before, after, from, to)
end

#assert_difference(expression, difference = 1) { ... } ⇒ nil

Passes when the block changes the value of expression by difference. The expression is a lambda, passed positionally (Rails’ String expression needs eval).

Examples:

assert_difference(-> { Article.count }, 1) do
  post "/articles", params: { article: { title: "x" } }
end

Parameters:

  • expression (Proc) —

    a lambda answering an Integer

  • difference (Integer) (defaults to: 1)

Yields:

  • the code that makes the change

Returns:

  • (nil) —

    not the block’s value, as in Rails: one return type per method name (spikes/NOTES.md rules 10, 34)



435
436
437
438
439
440
# File 'cybertrain/test/assertions.rb', line 435

def assert_difference(expression, difference = 1)
  before = expression.call
  yield
  after = expression.call
  Cybertrain::Test.check_difference(before, after, difference)
end

#assert_emails(count) { ... } ⇒ nil

Passes when the block delivered count mails: the messages Mailer.deliveries gained during it, after the mail queued in it with deliver_later was delivered (the “cybertrain mail” jobs queued in the block are performed first; jobs of other kinds stay queued). A mail job that fails (no sender, a refused address) fails the assertion with its error rather than counting short: assert_emails: the job "cybertrain mail" (id 2) raised ArgumentError: the from address is empty (now discarded). Without a block, passes when Mailer.deliveries holds count messages (it is emptied before every test).

Examples:

assert_emails 1 do
  post "/passwords", params: { email: "ann@example.com" }
end
assert_equal "Reset your password", Cybertrain::Mailer.deliveries.last.mail_subject

Parameters:

Yields:

  • the code that sends the mail

Returns:

  • (nil) —

    not the block’s value: one return type per method name (spikes/NOTES.md rules 10, 34)

Raises:



72
73
74
75
76
77
78
79
80
81
# File 'cybertrain/test/mail.rb', line 72

def assert_emails(count)
  before = 0
  if block_given?
    before = Cybertrain::Mailer.deliveries.size
    floor = Cybertrain::Test::Mail.job_floor
    yield
    Cybertrain::Test::Mail.deliver_queued(floor, "assert_emails")
  end
  Cybertrain::Test.check_emails(count, Cybertrain::Mailer.deliveries.size - before)
end

#assert_empty(object) ⇒ nil

Passes when a String, Array or Hash is empty.

Parameters:

  • object (String, Array, Hash)

Returns:

  • (nil)


383
384
385
# File 'cybertrain/test/assertions.rb', line 383

def assert_empty(object)
  Cybertrain::Test.check_empty(object, true)
end

#assert_enqueued_jobs(count, kind = "")

This method returns an undefined value.

Passes when count jobs are queued (rows in state queued, not yet run), of kind when one is given.

Examples:

post "/comments", ...
assert_enqueued_jobs 1, "NotifyCommentJob"

Parameters:

  • count (Integer)
  • kind (String) (defaults to: "") —

    ”” counts every kind



142
143
144
145
146
147
148
149
# File 'cybertrain/test/jobs.rb', line 142

def assert_enqueued_jobs(count, kind = "")
  Cybertrain::Test.count_assertion
  got = Cybertrain::Test::Jobs.queued_count(kind)
  return if got == count

  what = kind.empty? ? "jobs" : "#{kind.inspect} jobs"
  flunk("expected #{count} enqueued #{what}, got #{got}")
end

#assert_enqueued_with(kind, args = Cybertrain::Cast.empty_hash)

This method returns an undefined value.

Passes when at least one job of kind is queued whose args contain every given key with an equal value. Both sides are compared as Cast.str, so "user_id" => 1 matches a JSON 1 (and “1”). A Symbol key is read as its name, so user_id: 1 works too.

Examples:

assert_enqueued_with "WelcomeJob", { "user_id" => user.id }
assert_enqueued_with "WelcomeJob", user_id: user.id

Parameters:

  • kind (String) —

    the job’s kind (the class name for a Job::Base subclass)

  • args (Hash{String, Symbol => Object}) (defaults to: Cybertrain::Cast.empty_hash) —

    the keys that must match (none: any job of the kind)



177
178
179
180
181
182
183
184
185
186
187
# File 'cybertrain/test/jobs.rb', line 177

def assert_enqueued_with(kind, args = Cybertrain::Cast.empty_hash)
  Cybertrain::Test.count_assertion
  payloads = Cybertrain::Test::Jobs.queued_payloads(kind)
  payloads.each do |payload|
    return if Cybertrain::Test::Jobs.args_match?(payload, args)
  end

  wanted = args.empty? ? "" : " with #{Cybertrain::Test::Jobs.describe_args(args)}"
  queued = payloads.empty? ? "none queued" : "queued: #{payloads.join(", ")}"
  flunk("expected an enqueued #{kind.inspect} job#{wanted}; #{queued}")
end

#assert_equal(expected, actual)

This method returns an undefined value.

Passes when expected == actual; fails with Minitest’s text, the two values’ inspect on two lines (Expected: 1 / ` Actual: 0`).

Parameters:

  • expected (Object)
  • actual (Object)


680
681
682
# File 'cybertrain/test.rb', line 680

def assert_equal(expected, actual)
  Cybertrain::Test.check_equal(expected, actual)
end

#assert_in_delta(expected, actual, delta = 0.001) ⇒ nil

Passes when actual is within delta of expected (Minitest’s default delta, 0.001).

Examples:

assert_in_delta 0.3, 0.1 + 0.2

Parameters:

  • expected (Numeric)
  • actual (Numeric)
  • delta (Numeric) (defaults to: 0.001)

Returns:

  • (nil)


327
328
329
# File 'cybertrain/test/assertions.rb', line 327

def assert_in_delta(expected, actual, delta = 0.001)
  Cybertrain::Test.check_in_delta(expected, actual, delta)
end

#assert_includes(haystack, needle)

This method returns an undefined value.

Passes when a String contains needle.to_s or an Array includes needle. Any other haystack (a Hash) fails.

include? on a polymorphic receiver mis-dispatches under Spinel 2026.09.12 when the argument is also polymorphic (and String#include? does so as soon as SafeString is in the program), so the receiver is narrowed first and the String case goes through #index.

Examples:

assert_includes article.errors.full_messages, "Title can't be blank"
assert_includes client.response.body, "Hello Rails"

Parameters:

  • haystack (String, Array)
  • needle (Object)


707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'cybertrain/test.rb', line 707

def assert_includes(haystack, needle)
  Cybertrain::Test.count_assertion
  found = false
  case haystack
  when String
    n = needle.to_s
    found = !haystack.index(n).nil?
  when Array
    found = haystack.include?(needle)
  end
  unless found
    flunk("expected #{haystack.inspect} to include #{needle.inspect}")
  end
end

#assert_match(matcher, string) ⇒ nil

Passes when string matches: a Regexp is matched, a String is looked for as a substring.

Examples:

assert_match(/\A\d+\z/, response.body)

Parameters:

  • matcher (Regexp, String)
  • string (String)

Returns:

  • (nil)


339
340
341
# File 'cybertrain/test/assertions.rb', line 339

def assert_match(matcher, string)
  Cybertrain::Test.check_match(matcher, string, true)
end

#assert_nil(actual)

This method returns an undefined value.

Passes when actual is nil.

Parameters:

  • actual (Object)


688
689
690
691
# File 'cybertrain/test.rb', line 688

def assert_nil(actual)
  Cybertrain::Test.count_assertion
  flunk("expected nil, got #{actual.inspect}") unless actual.nil?
end

#assert_no_broadcasts(stream) { ... } ⇒ nil

Passes when nothing was broadcast to stream while the block ran, or, without a block, since the test began: assert_broadcasts(stream, 0) (and, as it, blind to rows a real server’s poller pruned).

Parameters:

Yields:

  • the code that must not broadcast (optional)

Returns:

  • (nil)


366
367
368
369
370
371
372
373
374
375
# File 'cybertrain/test/broadcasts.rb', line 366

def assert_no_broadcasts(stream)
  name = Cybertrain::Stream.name_for(stream)
  floor = Cybertrain::Test.case_message_floor
  if block_given?
    floor = Cybertrain::Test::Broadcasts.head_id
    yield
  end
  got = Cybertrain::Test::Broadcasts.payloads_after(name, floor).length
  Cybertrain::Test.check_broadcasts(name, 0, got)
end

#assert_no_difference(expression) { ... } ⇒ nil

Passes when the block leaves the value of expression unchanged.

Parameters:

  • expression (Proc) —

    a lambda answering an Integer

Yields:

  • the code that must not change it

Returns:

  • (nil) —

    not the block’s value, as in Rails: one return type per method name (spikes/NOTES.md rules 10, 34)



448
449
450
451
452
453
# File 'cybertrain/test/assertions.rb', line 448

def assert_no_difference(expression)
  before = expression.call
  yield
  after = expression.call
  Cybertrain::Test.check_difference(before, after, 0)
end

#assert_no_emails { ... } ⇒ nil

Passes when the block delivered no mail: assert_emails(0) { }, the deliver_later mail queued in it included. Without a block, passes when Mailer.deliveries is empty.

Examples:

assert_no_emails { post "/passwords", params: { email: "nobody@example.com" } }

Yields:

  • the code that must send no mail

Returns:

  • (nil)

Raises:



92
93
94
95
96
97
98
99
100
101
# File 'cybertrain/test/mail.rb', line 92

def assert_no_emails
  before = 0
  if block_given?
    before = Cybertrain::Mailer.deliveries.size
    floor = Cybertrain::Test::Mail.job_floor
    yield
    Cybertrain::Test::Mail.deliver_queued(floor, "assert_no_emails")
  end
  Cybertrain::Test.check_emails(0, Cybertrain::Mailer.deliveries.size - before)
end

#assert_no_enqueued_jobs(kind = "")

This method returns an undefined value.

Passes when no job is queued, of kind when one is given.

Examples:

assert_no_enqueued_jobs "WelcomeJob"

Parameters:

  • kind (String) (defaults to: "") —

    ”” checks every kind



157
158
159
160
161
162
163
164
# File 'cybertrain/test/jobs.rb', line 157

def assert_no_enqueued_jobs(kind = "")
  Cybertrain::Test.count_assertion
  got = Cybertrain::Test::Jobs.queued_count(kind)
  return if got == 0

  what = kind.empty? ? "jobs" : "#{kind.inspect} jobs"
  flunk("expected no enqueued #{what}, got #{got}")
end

#assert_no_match(matcher, string) ⇒ nil

Passes when string does not match (see #assert_match).

Parameters:

  • matcher (Regexp, String)
  • string (String)

Returns:

  • (nil)


348
349
350
# File 'cybertrain/test/assertions.rb', line 348

def assert_no_match(matcher, string)
  Cybertrain::Test.check_match(matcher, string, false)
end

#assert_not(object) ⇒ nil

Passes when object is false or nil (Rails’ name for refute).

Parameters:

  • object (Object)

Returns:

  • (nil)


399
400
401
# File 'cybertrain/test/assertions.rb', line 399

def assert_not(object)
  Cybertrain::Test.check_not(object)
end

#assert_not_empty(object) ⇒ nil

Passes when a String, Array or Hash is not empty.

Parameters:

  • object (String, Array, Hash)

Returns:

  • (nil)


391
392
393
# File 'cybertrain/test/assertions.rb', line 391

def assert_not_empty(object)
  Cybertrain::Test.check_empty(object, false)
end

#assert_not_equal(expected, actual) ⇒ nil

Passes when expected != actual.

Parameters:

  • expected (Object)
  • actual (Object)

Returns:

  • (nil)


357
358
359
# File 'cybertrain/test/assertions.rb', line 357

def assert_not_equal(expected, actual)
  Cybertrain::Test.check_not_equal(expected, actual)
end

#assert_not_includes(collection, object) ⇒ nil

Passes when a String does not contain object.to_s, or an Array does not include object (the opposite of assert_includes).

Parameters:

  • collection (String, Array)
  • object (Object)

Returns:

  • (nil)


375
376
377
# File 'cybertrain/test/assertions.rb', line 375

def assert_not_includes(collection, object)
  Cybertrain::Test.check_not_includes(collection, object)
end

#assert_not_nil(object) ⇒ nil

Passes when object is not nil.

Parameters:

  • object (Object)

Returns:

  • (nil)


365
366
367
# File 'cybertrain/test/assertions.rb', line 365

def assert_not_nil(object)
  Cybertrain::Test.check_not_nil(object)
end

#assert_nothing_raised { ... } ⇒ nil

Passes when the block raises nothing; otherwise fails naming the exception’s class and message. A failed assertion in the block fails with its own message.

Examples:

assert_nothing_raised { Article.find(article.id) }

Yields:

  • the code that must not raise

Returns:

  • (nil) —

    not the block’s value, as in Rails: one return type per method name (spikes/NOTES.md rules 10, 34)



412
413
414
415
416
417
418
419
420
# File 'cybertrain/test/assertions.rb', line 412

def assert_nothing_raised
  begin
    yield
    Cybertrain::Test.count_nothing_raised
  rescue StandardError => e
    Cybertrain::Test.check_nothing_raised(e)
  end
  nil
end

#assert_raises(expected = "") { ... } ⇒ String

Passes when the block raises the exception expected names, and answers that exception’s message, a String. A Class matches that class or a subclass, as Minitest’s does (assert_raises(ArgumentError), assert_raises(NotImplementedError), assert_raises(Cybertrain::DB::Error)); a String matches a class whose name contains it ("RecordNotFound"); nothing given matches any StandardError. The failures are Minitest’s: [ArgumentError] exception expected, not with the raised class and message on the next two lines, or ArgumentError expected but nothing was raised.

Unlike Rails (Minitest answers the exception), the answer is already the message: where Rails writes error = assert_raises(X) { ... } and then error.message, write message = assert_raises(X) { ... } and use message itself.

An exception that is not a StandardError (SystemExit, Interrupt, NoMemoryError, …) and is not the one expected is raised on untouched. A failed assertion inside the block is not “the expected exception”: AssertionFailed is a StandardError, so it is raised on (the test fails with that assertion’s message) unless expected names AssertionFailed, which is how the assertion helpers themselves are tested (assert_raises("AssertionFailed") { ... }).

Ruby’s own exception classes answer no superclass under Spinel, so a subclass is recognised above them from a table of their parents (the Errno family, JSON’s, Encoding’s, URI’s and the core classes); a built-in class outside it fails with its name, asking for the exact class or the name form (assert_raises("Name")).

Examples:

message = assert_raises(Cybertrain::RecordNotFound) { Article.find(999) }
assert_includes message, "id=999"

Parameters:

  • expected (Class, String) (defaults to: "") —

    the exception’s class, or part of its name

Yields:

  • the code that must raise

Returns:

  • (String) —

    the exception’s message (not the exception)



757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'cybertrain/test.rb', line 757

def assert_raises(expected = "")
  Cybertrain::Test.count_assertion
  message = ""
  raised = false
  begin
    yield
  rescue Exception => e
    # Exception, so NotImplementedError and other non-StandardErrors can be
    # expected; the helper raises on what was not. One clause only (a
    # second `=> e` of another type in this yielding method is untested
    # under Spinel, NOTES rule 32); the class is told
    # apart by name in the helper, which reads `name.to_s` (Class#name is
    # nil for an anonymous class under CRuby, and a NoMethodError from
    # here would replace the exception being asserted on).
    Cybertrain::Test.raise_unless_expected(expected, e)
    raised = true
    message = e.message
  end
  Cybertrain::Test.check_raised(expected, raised)
  message
end

#assert_redirected_to(response, path)

This method returns an undefined value.

Passes when the response is a 3xx whose Location is path; an absolute URL on the application’s host (www.example.com, or Cybertrain.url_root’s, as the *_url helpers write) counts as its path, on either side.

Examples:

assert_redirected_to res, "/articles/#{Article.last.id}"

Parameters:



837
838
839
# File 'cybertrain/test/client.rb', line 837

def assert_redirected_to(response, path)
  Cybertrain::Test.check_redirect(response, path)
end

#assert_response(response, expected)

This method returns an undefined value.

assert_response res, :ok / :not_found / 201 …; :redirect accepts any 3xx.

Symbols: every one Controller::STATUS_SYMBOLS accepts (:ok, :created, :accepted, :no_content, :see_other, :bad_request, :unauthorized, :forbidden, :not_found, :conflict, :payload_too_large, :unsupported_media_type, :unprocessable_entity, :too_many_requests, :service_unavailable, …), each standing for its one code, plus :success (2xx), :redirect (3xx), :missing (404) and :error (exactly 500; Rails takes any 5xx). Needs cybertrain/test/client.

Parameters:



824
825
826
# File 'cybertrain/test/client.rb', line 824

def assert_response(response, expected)
  Cybertrain::Test.check_response(response, expected)
end

#assert_select(selector, equality = nil, count: nil, minimum: nil, maximum: nil, text: nil) ⇒ Array<Cybertrain::Test::HtmlNode>

Checks the last rendered HTML (render_inline’s, or the last response of an integration test) for elements matching selector, and answers them. With no option at least one must match. The second argument may be Rails’ positional form: a String or Regexp (the text), an Integer (the count), a Range (2..3: at least 2, at most 3), true (at least one) or false (none). text: is a String, compared with each element’s text after collapsing whitespace and stripping, or a Regexp matched against that text; only the elements whose text matches are counted and answered.

The nested block form (assert_select "ul" do ... end) is not supported; cybertrain test refuses it at gen, and here it fails.

Examples:

get articles_path
assert_select "ul#articles > li", count: 2
assert_select "h1", "Articles"
assert_select "form[action=\"/articles\"] input[name=\"article[title]\"]"

Parameters:

  • selector (String) —

    see cybertrain/test/select.rb for the subset

  • equality (String, Regexp, Integer, Range, true, false, nil) (defaults to: nil)
  • count (Integer, nil) (defaults to: nil) —

    exactly this many

  • minimum (Integer, nil) (defaults to: nil) —

    at least

  • maximum (Integer, nil) (defaults to: nil) —

    at most

  • text (String, Regexp, nil) (defaults to: nil)

Returns:

Raises:



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'cybertrain/test/select.rb', line 527

def assert_select(selector, equality = nil, count: nil, minimum: nil, maximum: nil, text: nil)
  if block_given?
    message = "assert_select: the nested block form is not supported (selector: #{selector.inspect})"
    Cybertrain::Test.fail_with(message)
  end
  want_text = text
  want_count = Cybertrain::Test.select_bound("count", count)
  want_min = Cybertrain::Test.select_bound("minimum", minimum)
  want_max = Cybertrain::Test.select_bound("maximum", maximum)
  if want_min >= 0 && want_max >= 0 && want_min > want_max
    message = "assert_select: minimum: #{want_min} is above maximum: #{want_max}"
    raise ArgumentError, message
  end
  # Rails takes the count positionally or as options, not both.
  counted = want_count >= 0 || want_min >= 0 || want_max >= 0
  case equality
  when nil then nil
  when String, Regexp
    unless text.nil?
      message = "assert_select: give the text once, as the second argument or as text:"
      raise ArgumentError, message
    end
    want_text = equality
  when Integer, true, false
    if counted
      message = "assert_select: give the count once, as the second argument (#{equality.inspect}) or as count:, minimum: and maximum:"
      raise ArgumentError, message
    end
    case equality
    when Integer then want_count = Cybertrain::Test.select_bound("count", equality)
    when true then want_min = 1
    else want_count = 0
    end
  when Range
    if counted
      message = "assert_select: give the count once, as the second argument (#{equality.inspect}) or as count:, minimum: and maximum:"
      raise ArgumentError, message
    end
    # Rails' `assert_select "li", 2..3`: at least the first, at most the
    # last (one less for `...`).
    if equality.begin.nil? || equality.end.nil?
      message = "assert_select: a Range count needs both ends (got #{equality.inspect})"
      raise ArgumentError, message
    end
    want_min = Cybertrain::Test.select_bound("count", equality.first)
    high = equality.last.to_i
    high -= 1 if equality.exclude_end?
    want_max = Cybertrain::Test.select_bound("count", high)
    if want_min > want_max
      message = "assert_select: minimum: #{want_min} is above maximum: #{want_max}"
      raise ArgumentError, message
    end
  else
    message = "assert_select: the second argument must be a String, a Regexp, an Integer, a Range, true or false"
    raise ArgumentError, message
  end
  # An unsupported selector is named before anything else.
  Cybertrain::Test::Selector.parse(selector)
  Cybertrain::Test.check_rendered
  html = Cybertrain::Test.last_html
  nodes = Cybertrain::Test.select_nodes(selector, html)
  label = ""
  found = Array.new(0) { Cybertrain::Test::HtmlNode.new("", 0, -1, 0) }
  case want_text
  when nil
    found = nodes
  when Regexp
    label = want_text.inspect
    nodes.each do |node|
      seen = Cybertrain::Test.squished_text(node.node_text)
      Cybertrain::Test.check_valid_text(node, seen)
      found << node if seen.match?(want_text)
    end
  else
    wanted = want_text.to_s
    label = wanted.inspect
    nodes.each { |node| found << node if Cybertrain::Test.squished_text(node.node_text) == wanted }
  end
  Cybertrain::Test.check_select(selector, found.length, want_count, want_min, want_max, label, html)
  found
end

#assert_turbo_stream(action:, target:, count: 1) ⇒ nil

Passes when the last response (or render_inline) of this test holds exactly count <turbo-stream action="..." target="..."> elements, as turbo-rails’ assertion does (count 1 by default). target is a DOM id or a record (its dom_id, "article_12"); "" matches a stream with no target (refresh). After an integration request the response must be text/vnd.turbo-stream.html (turbo-rails’ media type check; its status: :ok check is not made: assert the status with assert_response). With nothing requested or rendered in this test it fails (“No response yet”). The content of the streams’ templates is not read; turbo-rails’ block form and targets: are not offered.

Examples:

post article_comments_path(article), params: { comment: { body: "Hi" } },
     headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_turbo_stream action: "append", target: "comments"

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    for a negative count



397
398
399
400
401
402
# File 'cybertrain/test/broadcasts.rb', line 397

def assert_turbo_stream(action:, target:, count: 1)
  id = Cybertrain::Turbo.target_text(target)
  Cybertrain::Test.check_turbo_source
  streams = Cybertrain::Test.turbo_stream_nodes(Cybertrain::Test.last_html)
  Cybertrain::Test.check_turbo_stream(action.to_s, id, count, streams)
end

#clear_enqueued_jobs ⇒ Integer

Deletes every queued job, so the next test starts from an empty queue.

Returns:

  • (Integer) —

    how many rows were deleted



237
238
239
240
241
242
243
244
245
# File 'cybertrain/test/jobs.rb', line 237

def clear_enqueued_jobs
  Cybertrain::Job.ensure_installed
  removed = 0
  Cybertrain::DB.with do |c|
    c.execute("DELETE FROM cybertrain_jobs WHERE state = 'queued'")
    removed = c.changes
  end
  removed
end

#flunk(message)

This method returns an undefined value.

Fails the current case.

Parameters:

  • message (String)

Raises:



650
651
652
# File 'cybertrain/test.rb', line 650

def flunk(message)
  raise Cybertrain::Test::AssertionFailed, message
end

#freeze_time { ... } ⇒ nil

travel_to(Time.current): time stops where it is.

Yields:

  • the code that runs on the frozen clock; the previous clock comes back after it

Returns:

  • (nil)


57
58
59
60
61
62
63
64
65
# File 'cybertrain/test/time_helpers.rb', line 57

def freeze_time
  target = Time.current
  if block_given?
    Cybertrain::Clock.travel_during(target) { yield }
  else
    Cybertrain::Clock.travel_to(target)
  end
  nil
end

#perform_enqueued_jobs(now = Time.current) ⇒ Integer

Without a block: runs every job due at now on the calling thread, until none is due (Job.work_one), and returns how many it ran. A retry the job scheduled for later is left queued; pass a later now to run it.

With a block (Rails’ inline form): runs the block, then performs on the calling thread every job queued during it, and the jobs those queue, whatever their run_at, in enqueue order (Job.work_one_after), and returns how many distinct jobs it ran; now is not used. Jobs queued before the block stay queued. As Rails’ inline jobs raise into the test, a job whose attempt ends failed or rescheduled (its handler raised), or a mail the framework discarded (no sender, a refused address), fails the test at once with its kind and error: perform_enqueued_jobs: the job "BoomJob" (id 3) raised RuntimeError: boom (now queued). It is not retried in the block. A job the application discards on purpose (discard_on) counts as performed, as in Rails.

Either form fails the test after 10,000 jobs: a job that enqueues itself would otherwise never let the test end.

Examples:

post "/signup", ...
assert_equal 1, perform_enqueued_jobs

the block form

performed = perform_enqueued_jobs { ReminderJob.perform_in(3600, { "id" => 1 }) }

Parameters:

  • now (Time) (defaults to: Time.current)

Returns:

Raises:



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'cybertrain/test/jobs.rb', line 216

def perform_enqueued_jobs(now = Time.current)
  if block_given?
    floor = Cybertrain::Test::Jobs.max_id
    yield
    return Cybertrain::Test::Jobs.perform_after(floor, "", "perform_enqueued_jobs")
  end

  count = 0
  at = now.to_i
  while Cybertrain::Job.work_one(at)
    count += 1
    if count >= Cybertrain::Test::Jobs::PERFORM_LIMIT
      flunk("perform_enqueued_jobs ran 10000 jobs; a job re-enqueues itself due at once")
    end
  end
  count
end

#refute(condition, message = "expected condition to be falsy")

This method returns an undefined value.

Passes when the condition is false or nil.

Parameters:

  • condition (Object)
  • message (String) (defaults to: "expected condition to be falsy") —

    the failure message



669
670
671
672
# File 'cybertrain/test.rb', line 669

def refute(condition, message = "expected condition to be falsy")
  Cybertrain::Test.count_assertion
  flunk(message) if condition
end

#render_inline(component = nil, content: "", partial: "", locals: {}) ⇒ String

Renders a component (render_inline(CardComponent.new(title: "x")), its content as content:) or a partial (render_inline(partial: "articles/form", locals: { article: Article.new })) outside any request, answers the HTML and keeps it for assert_select (spec section 9.1). Rails answers a Nokogiri fragment and takes the content as a block; here the answer is the String and a block is refused. Request-bound helpers raise Views::OutsideRequest, as in Views.render_partial.

Examples:

html = render_inline(partial: "articles/form", locals: { article: Article.new })
assert_select "form[action=\"/articles\"] input[name=\"article[title]\"]"
assert_includes html, "Save"

Parameters:

  • component (Cybertrain::Component, nil) (defaults to: nil)
  • content (String) (defaults to: "") —

    the component’s content, unescaped

  • partial (String) (defaults to: "") —

    a partial’s name, as render takes it

  • locals (Hash) (defaults to: {}) —

    the partial’s locals

Returns:

  • (String) —

    the HTML

Raises:

  • (ArgumentError) —

    for neither or both of a component and partial:, for content: with a partial, locals: with a component, and for a block



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'cybertrain/test/views.rb', line 72

def render_inline(component = nil, content: "", partial: "", locals: {})
  if block_given?
    message = "render_inline: pass the content as content:, not a block"
    raise ArgumentError, message
  end
  if component.nil? == (partial == "")
    message = "render_inline: pass a component or partial:, not #{component.nil? ? "neither" : "both"}"
    raise ArgumentError, message
  end
  html = ""
  if partial == ""
    unless locals.empty?
      message = "render_inline: locals: are for a partial; a component takes its values in new(...)"
      raise ArgumentError, message
    end
    html = Cybertrain::Views.render_component(component, content).to_s
  else
    unless content == ""
      message = "render_inline: content: is for a component; a partial takes locals:"
      raise ArgumentError, message
    end
    html = Cybertrain::Views.render_partial(partial, locals).to_s
  end
  Cybertrain::Test.last_html = html
  html
end

#setup(&block) ⇒ nil

Registers a block run before every case of this file, after the reset hooks; several run in the order written. In a test class (the class form) setup do becomes the class’s def setup instead.

Examples:

setup do
  Cybertrain.config.http_allow_private = true
end

Returns:

  • (nil)


629
630
631
# File 'cybertrain/test.rb', line 629

def setup(&block)
  Cybertrain::Test.add_setup(block)
end

#teardown(&block) ⇒ nil

Registers a block run after every case of this file, whatever happened in it; several run in the reverse of the order written.

Examples:

teardown do
  Cybertrain.config.http_allow_private = false
end

Returns:

  • (nil)


641
642
643
# File 'cybertrain/test.rb', line 641

def teardown(&block)
  Cybertrain::Test.add_teardown(block)
end

#test(name, &block)

This method returns an undefined value.

Registers a test case, run in order by Cybertrain::Test.run!.

Examples:

test "POST /articles creates an article" do
  ...
end

Parameters:

  • name (String)


616
617
618
# File 'cybertrain/test.rb', line 616

def test(name, &block)
  Cybertrain::Test.register(name, block)
end

#travel(seconds) { ... } ⇒ nil

travel_to(Time.current + seconds).

Examples:

freeze_time
travel 6 * 60

Parameters:

Yields:

  • the code that runs at the new time; the previous clock comes back after it

Returns:

  • (nil)


43
44
45
46
47
48
49
50
51
# File 'cybertrain/test/time_helpers.rb', line 43

def travel(seconds)
  target = Time.current + seconds
  if block_given?
    Cybertrain::Clock.travel_during(target) { yield }
  else
    Cybertrain::Clock.travel_to(target)
  end
  nil
end

#travel_back ⇒ nil

Returns the clock to real time.

Returns:

  • (nil)


70
71
72
# File 'cybertrain/test/time_helpers.rb', line 70

def travel_back
  Cybertrain::Clock.travel_back
end

#travel_to(time) { ... } ⇒ nil

Sets the clock to time and holds it there.

Examples:

travel_to Time.utc(2026, 1, 1) do
  assert_equal Time.utc(2026, 1, 1), Time.current
end

Parameters:

Yields:

  • the code that runs at time; the previous clock comes back after it

Returns:

  • (nil)


26
27
28
29
30
31
32
33
# File 'cybertrain/test/time_helpers.rb', line 26

def travel_to(time)
  if block_given?
    Cybertrain::Clock.travel_during(time) { yield }
  else
    Cybertrain::Clock.travel_to(time)
  end
  nil
end