CyberTrain API
The methods an application calls: in controllers, models, migrations,
config/routes.rb, config/app.rb and tests. New to CyberTrain? Start with
the tutorial.
The guides cover the rest: installing and the CLI,
how it works and the differences from Rails,
models, requests,
configuration,
background work and operations,
outbound HTTP, WebSocket feeds and e-mail
and testing.
These pages are generated by YARD from the
framework’s source, cybertrain/, and only from what is marked as part of
the public API; everything else there is internal. Some of the API is not in
the framework at all: spin run gen writes it into each application’s
gen/ directory, and it is documented here through the classes
examples/blog
generates (Article, ArticleRelation, Gen::UrlHelpers).
Where things are
| You write | Reference |
|---|---|
class ArticlesController < ApplicationController |
Cybertrain::Controller: before_action, skip_before_action, rate_limit (Cybertrain::RateLimit), rescue_from, render, redirect_to, head |
user.password = ..., user.authenticate(...) (from cybertrain generate authentication) |
Cybertrain::Password: hash, verify?, needs_rehash?, iterations= |
params[:id], params.require(:article).permit(...) |
Cybertrain::Params |
session[...], flash[...] |
Cybertrain::Session, Cybertrain::Flash |
request.header(...), request.client_ip, response.set_header(...), cookies |
Cybertrain::Request, Cybertrain::Response, Cybertrain::Cookies |
Article.where(...).order(...).to_a, Article.find(id) |
Article and ArticleRelation (generated), Cybertrain::Relation |
article.save, article.update(...), article.errors |
Cybertrain::Model, Cybertrain::Errors |
validates, before_save { \|r\| ... } in app/models/ |
Cybertrain::Model.validates, Cybertrain::Model.before_save and the other callbacks |
article.comments, comment.article |
Article#comments, Comment#article (from foreign keys) |
config/routes.rb |
Cybertrain::Routes.draw, Cybertrain::Gen::Mapper (resources, resource, get …) |
article_path(@article) |
Gen::UrlHelpers (generated), Cybertrain.url_root |
db/migrate/*.rb |
Cybertrain::Migration::Base, Cybertrain::Schema::TableDef |
Cybertrain::WebSocket.subscribe("trades", url).on_open { ... }.on_message { ... } in config/app.rb |
Cybertrain::WebSocket (require "cybertrain/websocket"): Cybertrain::WebSocket.subscribe, Cybertrain::WebSocket::Subscription, Cybertrain::WebSocket::Connection, Cybertrain::WebSocket.feed_status; one connection: Cybertrain::WebSocket::Client; Cybertrain::Background |
config/app.rb |
Cybertrain.configure, Cybertrain::Config |
Cybertrain.logger.info(...), Cybertrain.logger.tagged("billing") { ... }, request.request_id |
Cybertrain::Logger, Cybertrain::Logger::Scope, Cybertrain::RequestId |
Cybertrain.error.report(e), Cybertrain.error.subscribe(...) |
Cybertrain::ErrorReporter, Cybertrain::ErrorSubscriber, Cybertrain::ErrorEvent; the Sentry sender Cybertrain::ErrorReporter::SentrySender (require "cybertrain/error_reporter/sentry"), Cybertrain::SentryDsn |
test/*.rb |
Cybertrain::Test, Cybertrain::Test::Client, and the assertions below |
app/views/**/*.html.erb |
Template language: helpers (link_to, form_with, …), the form builder and what a template may call |
| HTML from Ruby | Cybertrain::Html, Cybertrain::SafeString |
Exceptions you will meet
| Exception | Raised by | Unhandled, the request gets |
|---|---|---|
| Cybertrain::RecordNotFound | find, Cybertrain::Model#reload |
500; the generated ApplicationController rescues it to a 404 |
| Cybertrain::RecordInvalid | Cybertrain::Model#save! | 500 |
| Cybertrain::Params::ParameterMissing | Cybertrain::Params#require | 400 |
| Cybertrain::BodyUndecodable, Cybertrain::BodyTooLarge | Cybertrain::Request#decoded_body on a corrupt or unsupported Content-Encoding, or a body that would inflate past its size limit |
400 |
ArgumentError |
order with anything but column [ASC\|DESC], render with the wrong options |
500 |
Cybertrain::DB::Error |
SQLite refusing a query (a NOT NULL or foreign key constraint, a missing column) | 500 |
Cybertrain::Controller.rescue_from matches the exception’s class exactly.
In production a bare error response is replaced by public/<status>.html
when that file exists; in development a 500 shows the exception’s class,
message and template line.
Assertions
Top-level methods for test/*.rb (see Cybertrain::Test):
| Assertion | Passes when |
| — | — |
| assert(condition, message = ...) | the condition is truthy |
| refute(condition, message = ...) | it is false or nil |
| assert_equal(expected, actual) | expected == actual (a failure prints Expected: and ` Actual: on two lines, as Minitest) |
| assert_nil(actual) | it is nil |
| assert_includes(haystack, needle) | a String contains it, or an Array includes it |
| assert_raises(ArgumentError) { … } | the block raises that class or a subclass (or, given a String, a class whose name contains it); returns its message, a String (Rails answers the exception) |
| assert_not_equal(expected, actual) | expected != actual |
| assert_not_nil(object) | it is not nil |
| assert_not(object) | it is false or nil (refute) |
| assert_not_includes(haystack, needle) | the opposite of assert_includes |
| assert_empty(object) / assert_not_empty(object) | a String, Array or Hash is (is not) empty |
| assert_in_delta(expected, actual, delta = 0.001) | the two numbers are within delta |
| assert_match(matcher, string) / assert_no_match | a Regexp matches (a String is found) in it (or not) |
| assert_nothing_raised { … } | the block raises nothing |
| assert_difference(-> { Article.count }, 1) { … } | the block changes the lambda's value by that much |
| assert_no_difference(-> { Article.count }) { … } | it leaves it unchanged |
| assert_changes(-> { article.reload.title }, from: “a”, to: “b”) { … } | it changes the value (from and to, when given) |
| flunk(message) | never |
| assert_response(response, :ok) | the status matches (an Integer, or :success, :redirect, :not_found, ...) |
| assert_redirected_to(response, “/path”)` | it is a redirect to exactly that Location |
assert_response and assert_redirected_to come with
require "cybertrain/test/client". Each is documented on the
Top Level Namespace page. In an
ActionDispatch::IntegrationTest both read the last response:
assert_response :success, assert_redirected_to "/articles/1".
assert_select(selector, equality = nil, count:, minimum:, maximum:, text:)
(require "cybertrain/test/select", which cybertrain/test_help loads)
checks the last rendered HTML, the last render_inline or the last
response of an integration test, and answers the matching
Cybertrain::Test::HtmlNodes: assert_select "ul > li", count: 2,
assert_select "h1", "Hello", assert_select "table", false. Selectors
are a tag, .class, #id, [attr], [attr="v"], compounds, the ` ` and
> combinators and lists; other forms fail with their name.
render_inline(component, content: "") and render_inline(partial:,
locals: {}) (require "cybertrain/test/views") render outside a request,
answer the HTML and keep it for assert_select; a component test
inherits ViewComponent::TestCase.
assert_broadcasts(stream, count) { } (require "cybertrain/test/broadcasts",
which cybertrain/test_help loads) counts the rows written to
cybertrain_messages for a stream name or a record (Cybertrain::Stream.name_for)
while the block runs, or since the test began without a block, and answers
their payloads; assert_no_broadcasts(stream) expects none.
assert_turbo_stream action: "append", target: "comments" (a DOM id or a
record; count: 1 by default, as turbo-rails) checks the last response or
render of the test for that <turbo-stream> element; a response must be
text/vnd.turbo-stream.html (turbo-rails’ status check is left to
assert_response).
The job helpers come with require "cybertrain/test/jobs":
assert_enqueued_jobs(count, kind = ""), assert_no_enqueued_jobs(kind = ""),
assert_enqueued_with(kind, args = {}) (args compared as strings, so
"user_id" => 1 matches a JSON 1), perform_enqueued_jobs(now = Time.current)
(runs the due jobs, returns how many; with a block, runs the block and then
every job queued in it, and the jobs those queue, whatever their run_at)
and clear_enqueued_jobs.
In the test environment Cybertrain.config.mail_delivery_method is :test:
a delivery is checked and stored in Cybertrain::Mailer.deliveries (emptied
before every test) instead of connecting. assert_emails(count) { ... }
counts the mail the block delivered, deliver_later included (its jobs are
performed first), and assert_no_emails { ... } is assert_emails(0); both
come with cybertrain/test_help (require "cybertrain/test/mail"). A test
that reads mail at an SMTP receiver sets mail_delivery_method = :smtp.
Webhooks and e-mail the code under test sends are received in-process by
Cybertrain::Test::HttpReceiver (require "cybertrain/test/http_receiver")
and Cybertrain::Test::SmtpReceiver (require "cybertrain/test/smtp_receiver");
a WebSocket feed it consumes is played by Cybertrain::Test::WebSocketReceiver
(require "cybertrain/test/websocket_receiver"), and the error reports it
sends to Sentry by Cybertrain::Test::SentryReceiver (loaded by
cybertrain/test_help), whose envelopes are Cybertrain::Test::SentryEnvelopes.
Conventions on these pages
- Signatures and behaviour are those of the current
mainbranch; an application pins its framework version inspin.lock. - Many methods’ descriptions end with notes on the Spinel constraint behind a design choice. They explain the framework’s code; you can skip them.