repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/controller/controller_generator_spec.rb | spec/generators/rspec/controller/controller_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/controller/controller_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::ControllerGenerator, type: :generator do
setup_default_destination
describe 'request specs' do
subject(:filename) { file('spec/requests/posts_spec.rb') }
describe 'generated by default' do
before do
run_generator %w[posts]
end
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "Posts", #{type_metatag(:request)}/))
.and(contain('pending'))
end
end
describe 'skipped with a flag' do
before do
run_generator %w[posts --no-request_specs]
end
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
describe 'with actions' do
before do
run_generator %w[posts index custom_action]
end
it 'includes the standard boilerplate' do
expect(filename).to contain('get "/posts/index"')
.and(contain('get "/posts/custom_action"'))
end
end
describe 'with namespace and actions' do
subject(:filename) { file('spec/requests/admin/external/users_spec.rb') }
before do
run_generator %w[admin::external::users index custom_action]
end
it 'includes the standard boilerplate' do
expect(filename).to contain(/^RSpec.describe "Admin::External::Users", #{type_metatag(:request)}/)
.and(contain('get "/admin/external/users/index"'))
.and(contain('get "/admin/external/users/custom_action"'))
end
end
end
describe 'view specs' do
describe 'are not generated' do
describe 'with no-view-spec flag' do
before do
run_generator %w[posts index show --no-view-specs]
end
describe 'index.html.erb' do
subject(:filename) { file('spec/views/posts/index.html.erb_spec.rb') }
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
end
describe 'with no actions' do
before do
run_generator %w[posts]
end
describe 'index.html.erb' do
subject(:filename) { file('spec/views/posts/index.html.erb_spec.rb') }
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
end
describe 'with --no-template-engine' do
before do
run_generator %w[posts index --no-template-engine]
end
describe 'index.html.erb' do
subject(:filename) { file('spec/views/posts/index.html._spec.rb') }
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
end
end
describe 'are generated' do
describe 'with default template engine' do
before do
run_generator %w[posts index show]
end
describe 'index.html.erb' do
subject(:filename) { file('spec/views/posts/index.html.erb_spec.rb') }
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "posts\/index.html.erb", #{type_metatag(:view)}/))
end
end
describe 'show.html.erb' do
subject(:filename) { file('spec/views/posts/show.html.erb_spec.rb') }
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "posts\/show.html.erb", #{type_metatag(:view)}/))
end
end
end
describe 'with haml' do
before do
run_generator %w[posts index --template_engine haml]
end
describe 'index.html.haml' do
subject(:filename) { file('spec/views/posts/index.html.haml_spec.rb') }
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "posts\/index.html.haml", #{type_metatag(:view)}/))
end
end
end
end
describe 'are removed' do
subject(:output) { run_generator %w[posts], behavior: :revoke }
it 'will remove the file' do
expect(output).to match('remove spec/views/posts')
end
end
end
describe 'routing spec' do
subject(:filename) { file('spec/routing/posts_routing_spec.rb') }
describe 'with no flag' do
before do
run_generator %w[posts seek and destroy]
end
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
describe 'with --routing-specs flag' do
describe 'without action parameter' do
before do
run_generator %w[posts --routing-specs]
end
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
describe 'with action parameter' do
before { run_generator %w[posts seek --routing-specs] }
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe 'PostsController', #{type_metatag(:routing)}/))
.and(contain(/describe 'routing'/))
.and(contain(/it 'routes to #seek'/))
.and(contain(/expect\(get: "\/posts\/seek"\).to route_to\("posts#seek"\)/))
end
end
end
describe 'with --no-routing-specs flag' do
before do
run_generator %w[posts seek and destroy --no-routing_specs]
end
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
end
describe 'controller specs' do
subject(:filename) { file('spec/controllers/posts_controller_spec.rb') }
it 'are not generated' do
expect(File.exist?(filename)).to be false
end
describe 'with --controller-specs flag' do
before do
run_generator %w[posts --controller-specs]
end
describe 'the spec' do
it 'includes the standard boilerplate' do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/))
end
end
end
describe 'with --no-controller_specs flag' do
before do
run_generator %w[posts --no-controller-specs]
end
it 'are skipped' do
expect(File.exist?(filename)).to be false
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/system/system_generator_spec.rb | spec/generators/rspec/system/system_generator_spec.rb | # Generators are not automatically loaded by rails
require 'generators/rspec/system/system_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::SystemGenerator, type: :generator do
setup_default_destination
describe "system specs" do
subject(:system_spec) { file("spec/system/posts_spec.rb") }
describe "are generated independently from the command line" do
before do
run_generator %w[posts]
end
describe "the spec" do
it "contains the standard boilerplate" do
expect(system_spec).to contain(/require 'rails_helper'/).and(contain(/^RSpec.describe "Posts", #{type_metatag(:system)}/))
end
end
end
describe "are not generated" do
before do
run_generator %w[posts --no-system-specs]
end
describe "the spec" do
it "does not exist" do
expect(File.exist?(system_spec)).to be false
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/scaffold/scaffold_generator_spec.rb | spec/generators/rspec/scaffold/scaffold_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/scaffold/scaffold_generator'
require 'support/generators'
require 'rspec/support/spec/in_sub_process'
RSpec.describe Rspec::Generators::ScaffoldGenerator, type: :generator do
include RSpec::Support::InSubProcess
setup_default_destination
if Rack::RELEASE < "3.1.0"
let(:unprocessable_status) { ":unprocessable_entity" }
else
let(:unprocessable_status) { ":unprocessable_content" }
end
describe 'standard request specs' do
subject(:filename) { file('spec/requests/posts_spec.rb') }
describe 'with no options' do
before { run_generator %w[posts --request_specs] }
it "includes the standard boilerplate" do
expect(
filename
).to(
contain("require 'rails_helper'")
.and(contain(/^RSpec.describe "\/posts", #{type_metatag(:request)}/))
.and(contain('GET /new'))
.and(contain(/"redirects to the created post"/))
.and(contain('get post_url(post)'))
.and(contain('redirect_to(post_url(Post.last))'))
.and(contain(/"redirects to the \w+ list"/))
)
expect(
filename
).to(
contain(/renders a response with 422 status \(i.e. to display the 'new' template\)/)
.and(contain(/renders a response with 422 status \(i.e. to display the 'edit' template\)/))
)
expect(filename).to contain(/expect\(response\).to have_http_status\(#{unprocessable_status}\)/)
end
end
describe 'with --no-request_specs' do
before { run_generator %w[posts --no-request_specs] }
it "is skipped" do
expect(File.exist?(filename)).to be false
end
end
describe 'with --api' do
before { run_generator %w[posts --api] }
it "includes the standard boilerplate" do
expect(
filename
).to(
contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "\/posts", #{type_metatag(:request)}/))
.and(contain('as: :json'))
.and(contain('renders a JSON response with the new post'))
.and(contain('renders a JSON response with errors for the new post'))
.and(contain('renders a JSON response with the post'))
.and(contain('renders a JSON response with errors for the post'))
)
expect(filename).not_to contain('get new_posts_path')
expect(filename).not_to contain(/"redirects to\w+"/)
expect(filename).not_to contain('get edit_posts_path')
end
end
describe 'in an engine' do
it 'generates files with Engine url_helpers' do
in_sub_process do
allow_any_instance_of(::Rails::Generators::NamedBase).to receive(:mountable_engine?).and_return(true)
run_generator %w[posts --request_specs]
expect(filename).to contain('Engine.routes.url_helpers')
end
end
end
end
describe 'standard controller spec' do
subject(:filename) { file('spec/controllers/posts_controller_spec.rb') }
describe 'with --controller_specs' do
before { run_generator %w[posts --controller_specs] }
it "includes the standard boilerplate" do
expect(
filename
).to(
contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/))
.and(contain(/GET #new/))
.and(contain(/"redirects to the created \w+"/))
.and(contain(/GET #edit/))
.and(contain(/"redirects to the \w+"/))
.and(contain(/"redirects to the \w+ list"/))
)
expect(filename).to contain(/renders a response with 422 status \(i.e. to display the 'new' template\)/)
.and(contain(/renders a response with 422 status \(i.e. to display the 'edit' template\)/))
expect(filename).to contain(/expect\(response\).to have_http_status\(#{unprocessable_status}\)/)
expect(filename).not_to contain(/"renders a JSON response with the new \w+"/)
expect(filename).not_to contain(/"renders a JSON response with errors for the new \w+"/)
expect(filename).not_to contain(/"renders a JSON response with the \w+"/)
expect(filename).not_to contain(/"renders a JSON response with errors for the \w+"/)
end
end
describe 'with no options' do
before { run_generator %w[posts] }
it 'skips the file' do
expect(File.exist?(filename)).to be false
end
end
describe 'with --api' do
before { run_generator %w[posts --controller_specs --api] }
it "includes the standard boilerplate" do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/))
.and(contain(/"renders a JSON response with the new \w+"/))
.and(contain(/"renders a JSON response with errors for the new \w+"/))
.and(contain(/"renders a JSON response with the \w+"/))
.and(contain(/"renders a JSON response with errors for the \w+"/))
expect(filename).not_to contain(/GET #new/)
expect(filename).not_to contain(/"redirects to the created \w+"/)
expect(filename).not_to contain(/display the 'new' template/)
expect(filename).not_to contain(/GET #edit/)
expect(filename).not_to contain(/"redirects to the \w+"/)
expect(filename).not_to contain(/display the 'edit' template/)
expect(filename).not_to contain(/"redirects to the \w+ list"/)
end
end
end
describe 'namespaced request spec' do
subject(:filename) { file('spec/requests/admin/posts_spec.rb') }
describe 'with default options' do
before { run_generator %w[admin/posts] }
it "includes the standard boilerplate" do
expect(filename).to contain(/^RSpec.describe "\/admin\/posts", #{type_metatag(:request)}/)
.and(contain('post admin_posts_url, params: { admin_post: valid_attributes }'))
.and(contain('admin_post_url(post)'))
.and(contain('Admin::Post.create'))
end
end
describe 'with --model-name' do
before { run_generator %w[admin/posts --model-name=post] }
it "includes the standard boilerplate" do
expect(filename).to contain('post admin_posts_url, params: { post: valid_attributes }')
.and(contain(' Post.create'))
expect(filename).not_to contain('params: { admin_post: valid_attributes }')
end
end
context 'with --api' do
describe 'with default options' do
before { run_generator %w[admin/posts --api] }
it "includes the standard boilerplate" do
expect(filename).to contain('params: { admin_post: valid_attributes }')
.and(contain('Admin::Post.create'))
end
end
describe 'with --model-name' do
before { run_generator %w[admin/posts --api --model-name=post] }
it "includes the standard boilerplate" do
expect(filename).to contain('params: { post: valid_attributes }')
.and(contain(' Post.create'))
expect(filename).not_to contain('params: { admin_post: valid_attributes }')
end
end
end
end
describe 'namespaced controller spec' do
subject(:filename) { file('spec/controllers/admin/posts_controller_spec.rb') }
describe 'with default options' do
before { run_generator %w[admin/posts --controller_specs] }
it "includes the standard boilerplate" do
expect(filename).to contain(/^RSpec.describe Admin::PostsController, #{type_metatag(:controller)}/)
.and(contain('post :create, params: {admin_post: valid_attributes}'))
.and(contain('Admin::Post.create'))
end
end
describe 'with --model-name' do
before { run_generator %w[admin/posts --model-name=post --controller_specs] }
it "includes the standard boilerplate" do
expect(filename).to contain('post :create, params: {post: valid_attributes}')
.and(contain(' Post.create'))
expect(filename).not_to contain('params: {admin_post: valid_attributes}')
end
end
context 'with --api' do
describe 'with default options' do
before { run_generator %w[admin/posts --api --controller_specs] }
it "includes the standard boilerplate" do
expect(filename).to contain('post :create, params: {admin_post: valid_attributes}')
.and(contain('Admin::Post.create'))
end
end
describe 'with --model-name' do
before { run_generator %w[admin/posts --api --model-name=post --controller_specs] }
it "includes the standard boilerplate" do
expect(filename).to contain('post :create, params: {post: valid_attributes}')
.and(contain(' Post.create'))
expect(filename).not_to contain('params: {admin_post: valid_attributes}')
end
end
end
end
describe 'view specs' do
describe 'with no options' do
before { run_generator %w[posts] }
describe 'edit' do
subject(:filename) { file("spec/views/posts/edit.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "(.*)\/edit", #{type_metatag(:view)}/))
.and(contain(/assign\(:post, post\)/))
.and(contain(/it "renders the edit (.*) form"/))
end
end
describe 'index' do
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "(.*)\/index", #{type_metatag(:view)}/))
.and(contain(/assign\(:posts, /))
.and(contain(/it "renders a list of (.*)"/))
selector =
if Rails.version.to_f < 8.1
/'div>p'/
else
/'div>div>div'/
end
expect(filename).to contain(selector)
end
end
describe 'new' do
subject(:filename) { file("spec/views/posts/new.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "(.*)\/new", #{type_metatag(:view)}/))
.and(contain(/assign\(:post, /))
.and(contain(/it "renders new (.*) form"/))
end
end
describe 'show' do
subject(:filename) { file("spec/views/posts/show.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/require 'rails_helper'/)
.and(contain(/^RSpec.describe "(.*)\/show", #{type_metatag(:view)}/))
.and(contain(/assign\(:post, /))
.and(contain(/it "renders attributes in <p>"/))
end
end
end
describe 'with multiple integer attributes index' do
before { run_generator %w[posts upvotes:integer downvotes:integer] }
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain('assert_select cell_selector, text: Regexp.new(2.to_s), count: 2')
.and(contain('assert_select cell_selector, text: Regexp.new(3.to_s), count: 2'))
end
end
describe 'with multiple float attributes index' do
before { run_generator %w[posts upvotes:float downvotes:float] }
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain('assert_select cell_selector, text: Regexp.new(2.5.to_s), count: 2')
.and(contain('assert_select cell_selector, text: Regexp.new(3.5.to_s), count: 2'))
end
end
describe 'with reference attribute' do
before { run_generator %w[posts title:string author:references] }
describe 'edit' do
subject(:filename) { file("spec/views/posts/edit.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assert_select "input\[name=\?\]", "post\[author_id\]/)
.and(contain(/assert_select "input\[name=\?\]", "post\[title\]/))
end
end
describe 'new' do
subject(:filename) { file("spec/views/posts/new.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assert_select "input\[name=\?\]", "post\[author_id\]"/)
.and(contain(/assert_select "input\[name=\?\]", "post\[title\]/))
end
end
end
describe 'with namespace' do
before { run_generator %w[admin/posts] }
describe 'edit' do
subject(:filename) { file("spec/views/admin/posts/edit.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:admin_post, admin_post\)/)
end
end
describe 'index' do
subject(:filename) { file("spec/views/admin/posts/index.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:admin_posts, /)
end
end
describe 'new' do
subject(:filename) { file("spec/views/admin/posts/new.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:admin_post, /)
end
end
describe 'show' do
subject(:filename) { file("spec/views/admin/posts/show.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:admin_post, /)
end
end
end
describe 'with namespace and --model-name' do
before { run_generator %w[admin/posts --model-name=Post] }
describe 'edit' do
subject(:filename) { file("spec/views/admin/posts/edit.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:post, post\)/)
end
end
describe 'index' do
subject(:filename) { file("spec/views/admin/posts/index.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:posts, /)
end
end
describe 'new' do
subject(:filename) { file("spec/views/admin/posts/new.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:post, /)
end
end
describe 'show' do
subject(:filename) { file("spec/views/admin/posts/show.html.erb_spec.rb") }
it "includes the standard boilerplate" do
expect(filename).to contain(/assign\(:post, /)
end
end
end
describe 'with --no-template-engine' do
before { run_generator %w[posts --no-template-engine] }
describe 'edit' do
subject(:filename) { file("spec/views/posts/edit.html._spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'index' do
subject(:filename) { file("spec/views/posts/index.html._spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'new' do
subject(:filename) { file("spec/views/posts/new.html._spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'show' do
subject(:filename) { file("spec/views/posts/show.html._spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
end
describe 'with --api' do
before { run_generator %w[posts --api] }
describe 'edit' do
subject(:filename) { file("spec/views/posts/edit.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'index' do
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'new' do
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'show' do
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
end
describe 'with --no-view-specs' do
before { run_generator %w[posts --no-view-specs] }
describe 'edit' do
subject(:filename) { file("spec/views/posts/edit.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'index' do
subject(:filename) { file("spec/views/posts/index.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'new' do
subject(:filename) { file("spec/views/posts/new.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'show' do
subject(:filename) { file("spec/views/posts/show.html.erb_spec.rb") }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
end
end
describe 'routing spec' do
subject(:filename) { file('spec/routing/posts_routing_spec.rb') }
describe 'with default options' do
before { run_generator %w[posts] }
it 'includes the standard boilerplate' do
expect(filename).to contain(/require "rails_helper"/)
.and(contain(/^RSpec.describe PostsController, #{type_metatag(:routing)}/))
.and(contain(/describe "routing"/))
.and(contain(/routes to #new/))
.and(contain(/routes to #edit/))
.and(contain('route_to("posts#new")'))
end
end
describe 'with --no-routing-specs' do
before { run_generator %w[posts --no-routing_specs] }
it "skips the file" do
expect(File.exist?(filename)).to be false
end
end
describe 'with --api' do
before { run_generator %w[posts --api] }
it 'skips the right content' do
expect(filename).not_to contain(/routes to #new/)
expect(filename).not_to contain(/routes to #edit/)
end
end
context 'with a namespaced name' do
subject(:filename) { file('spec/routing/api/v1/posts_routing_spec.rb') }
describe 'with default options' do
before { run_generator %w[api/v1/posts] }
it 'includes the standard boilerplate' do
expect(filename).to contain(/^RSpec.describe Api::V1::PostsController, #{type_metatag(:routing)}/)
.and(contain('route_to("api/v1/posts#new")'))
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/mailer/mailer_generator_spec.rb | spec/generators/rspec/mailer/mailer_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/mailer/mailer_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::MailerGenerator, type: :generator do
setup_default_destination
describe 'mailer spec' do
subject(:filename) { file('spec/mailers/posts_mailer_spec.rb') }
describe 'a spec is created for each action' do
before do
run_generator %w[posts index show]
end
it "includes the standard boilerplate" do
# Rails 5+ automatically appends Mailer to the provided constant so we do too
expect(
filename
).to(
contain(/require "rails_helper"/)
.and(contain(/^RSpec.describe PostsMailer, #{type_metatag(:mailer)}/))
.and(contain(/describe "index" do/))
.and(contain(/describe "show" do/))
)
end
end
describe 'creates placeholder when no actions specified' do
before do
run_generator %w[posts]
end
it "includes the standard boilerplate" do
expect(
filename
).to contain(/require "rails_helper"/).and(contain(/pending "add some examples to \(or delete\)/))
end
end
end
describe 'a fixture is generated for each action' do
before do
run_generator %w[posts index show]
end
describe 'index' do
subject(:filename) { file('spec/fixtures/posts/index') }
it "includes the standard boilerplate" do
expect(filename).to contain(/Posts#index/)
end
end
describe 'show' do
subject(:filename) { file('spec/fixtures/posts/show') }
it "includes the standard boilerplate" do
expect(filename).to contain(/Posts#show/)
end
end
end
describe 'a preview is generated for each action', skip: !RSpec::Rails::FeatureCheck.has_action_mailer_preview? do
before do
run_generator %w[posts index show]
end
subject(:filename) { file('spec/mailers/previews/posts_mailer_preview.rb') }
it "includes the standard boilerplate" do
expect(
filename
).to(
contain(/class PostsMailerPreview < ActionMailer::Preview/)
.and(contain(/def index/))
.and(contain(/PostsMailer.index/))
.and(contain(/def show/))
.and(contain(/PostsMailer.show/))
)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/model/model_generator_spec.rb | spec/generators/rspec/model/model_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/model/model_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::ModelGenerator, type: :generator do
setup_default_destination
it 'runs both the model and fixture tasks' do
gen = generator %w[posts]
expect(gen).to receive :create_model_spec
expect(gen).to receive :create_fixture_file
gen.invoke_all
end
it_behaves_like 'a model generator with fixtures', 'admin/posts', 'Admin::Posts'
it_behaves_like 'a model generator with fixtures', 'posts', 'Posts'
describe 'the generated files' do
describe 'without fixtures' do
before do
run_generator %w[posts]
end
describe 'the fixtures' do
it "will skip the file" do
expect(File.exist?(file('spec/fixtures/posts.yml'))).to be false
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/authentication/authentication_generator_spec.rb | spec/generators/rspec/authentication/authentication_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/authentication/authentication_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::AuthenticationGenerator, type: :generator do
setup_default_destination
it 'runs both the model and fixture tasks' do
gen = generator
expect(gen).to receive :create_user_spec
expect(gen).to receive :create_fixture_file
gen.invoke_all
end
describe 'the generated files' do
it 'creates the user spec' do
run_generator
expect(File.exist?(file('spec/models/user_spec.rb'))).to be true
end
describe 'with fixture replacement' do
before do
run_generator ['--fixture-replacement=factory_bot']
end
describe 'the fixtures' do
it "will skip the file" do
expect(File.exist?(file('spec/fixtures/users.yml'))).to be false
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/generator/generator_generator_spec.rb | spec/generators/rspec/generator/generator_generator_spec.rb | require 'generators/rspec/generator/generator_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::GeneratorGenerator, type: :generator do
setup_default_destination
describe "generator specs" do
subject(:generator_spec) { file("spec/generator/posts_generator_spec.rb") }
before do
run_generator %w[posts]
end
it "include the standard boilerplate" do
expect(generator_spec).to contain(/require 'rails_helper'/).and(contain(/^RSpec.describe "PostsGenerator", #{type_metatag(:generator)}/))
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/feature/feature_generator_spec.rb | spec/generators/rspec/feature/feature_generator_spec.rb | # Generators are not automatically loaded by rails
require 'generators/rspec/feature/feature_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::FeatureGenerator, type: :generator do
setup_default_destination
describe 'feature specs' do
describe 'are generated independently from the command line' do
before do
run_generator %w[posts]
end
describe 'the spec' do
subject(:feature_spec) { file('spec/features/posts_spec.rb') }
it 'includes the standard boilerplate' do
expect(
feature_spec
).to contain(/require 'rails_helper'/).and(contain(/^RSpec.feature "Posts", #{type_metatag(:feature)}/))
end
end
end
describe 'are generated with the correct namespace' do
before do
run_generator %w[folder/posts]
end
describe 'the spec' do
subject(:feature_spec) { file('spec/features/folder/posts_spec.rb') }
it 'includes the standard boilerplate' do
expect(feature_spec).to contain(/^RSpec.feature "Folder::Posts", #{type_metatag(:feature)}/)
end
end
end
describe 'are singularized appropriately with the --singularize flag' do
before do
run_generator %w[posts --singularize]
end
describe 'the spec' do
subject(:feature_spec) { file('spec/features/post_spec.rb') }
it "contains the singularized feature" do
expect(feature_spec).to contain(/^RSpec.feature "Post", #{type_metatag(:feature)}/)
end
end
end
describe "are not generated" do
before do
run_generator %w[posts --no-feature-specs]
end
describe "the spec" do
subject(:feature_spec) { file('spec/features/posts_spec.rb') }
it "does not exist" do
expect(File.exist?(feature_spec)).to be false
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/view/view_generator_spec.rb | spec/generators/rspec/view/view_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/view/view_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::ViewGenerator, type: :generator do
setup_default_destination
describe 'with default template engine' do
it 'generates a spec for the supplied action' do
run_generator %w[posts index]
file('spec/views/posts/index.html.erb_spec.rb').tap do |f|
expect(f).to contain(/require 'rails_helper'/)
expect(f).to contain(/^RSpec.describe "posts\/index", #{type_metatag(:view)}/)
end
end
describe 'with a nested resource' do
it 'generates a spec for the supplied action' do
run_generator %w[admin/posts index]
file('spec/views/admin/posts/index.html.erb_spec.rb').tap do |f|
expect(f).to contain(/require 'rails_helper'/)
expect(f).to contain(/^RSpec.describe "admin\/posts\/index", #{type_metatag(:view)}/)
end
end
end
end
describe 'with a specified template engine' do
it 'generates a spec for the supplied action' do
run_generator %w[posts index --template_engine haml]
file('spec/views/posts/index.html.haml_spec.rb').tap do |f|
expect(f).to contain(/require 'rails_helper'/)
expect(f).to contain(/^RSpec.describe "posts\/index", #{type_metatag(:view)}/)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/helper/helper_generator_spec.rb | spec/generators/rspec/helper/helper_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/helper/helper_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::HelperGenerator, type: :generator do
setup_default_destination
subject(:helper_spec) { file('spec/helpers/posts_helper_spec.rb') }
describe 'generated by default' do
before do
run_generator %w[posts]
end
it 'includes the standard boilerplate' do
expect(helper_spec).to contain(/require 'rails_helper'/).and(contain(/^RSpec.describe PostsHelper, #{type_metatag(:helper)}/))
end
end
describe 'skipped with a flag' do
before do
run_generator %w[posts --no-helper_specs]
end
it 'does not create the helper spec' do
expect(File.exist?(helper_spec)).to be false
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/mailbox/mailbox_generator_spec.rb | spec/generators/rspec/mailbox/mailbox_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/mailbox/mailbox_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::MailboxGenerator, type: :generator, skip: !RSpec::Rails::FeatureCheck.has_action_mailbox? do
setup_default_destination
describe 'the generated files' do
before { run_generator %w[forwards] }
subject(:mailbox_spec) { file('spec/mailboxes/forwards_mailbox_spec.rb') }
it 'generates the file' do
expect(
mailbox_spec
).to contain(/require 'rails_helper'/).and contain(/describe ForwardsMailbox, #{type_metatag(:mailbox)}/)
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/channel/channel_generator_spec.rb | spec/generators/rspec/channel/channel_generator_spec.rb | # Generators are not automatically loaded by Rails
require "generators/rspec/channel/channel_generator"
require 'support/generators'
RSpec.describe Rspec::Generators::ChannelGenerator, type: :generator, skip: !RSpec::Rails::FeatureCheck.has_action_cable_testing? do
setup_default_destination
before { run_generator %w[chat] }
subject(:channel_spec) { file("spec/channels/chat_channel_spec.rb") }
it "generates a channel spec file" do
expect(channel_spec).to contain(/require 'rails_helper'/).and(contain(/describe ChatChannel, #{type_metatag(:channel)}/))
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/request/request_generator_spec.rb | spec/generators/rspec/request/request_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/request/request_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::RequestGenerator, type: :generator do
setup_default_destination
it_behaves_like "a request spec generator"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/job/job_generator_spec.rb | spec/generators/rspec/job/job_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/job/job_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::JobGenerator, type: :generator, skip: !RSpec::Rails::FeatureCheck.has_active_job? do
setup_default_destination
describe 'the generated files' do
before { run_generator [file_name] }
subject(:job_spec) { file('spec/jobs/user_job_spec.rb') }
context 'with file_name without job as suffix' do
let(:file_name) { 'user' }
it 'creates the standard boiler plate' do
expect(job_spec).to contain(/require 'rails_helper'/).and(contain(/describe UserJob, #{type_metatag(:job)}/))
end
end
context 'with file_name with job as suffix' do
let(:file_name) { 'user_job' }
it 'creates the standard boiler plate' do
expect(job_spec).to contain(/require 'rails_helper'/).and(contain(/describe UserJob, #{type_metatag(:job)}/))
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/spec/generators/rspec/install/install_generator_spec.rb | spec/generators/rspec/install/install_generator_spec.rb | # Generators are not automatically loaded by Rails
require 'generators/rspec/install/install_generator'
require 'support/generators'
RSpec.describe Rspec::Generators::InstallGenerator, type: :generator do
def use_active_record_migration
match(/ActiveRecord::Migration\./m)
end
def content_for(file_name)
File.read(file(file_name))
end
def have_a_fixture_path
match(/^ config\.fixture_path = /m)
end
def have_fixture_paths
match(/^ config\.fixture_paths = /m)
end
def maintain_test_schema
match(/ActiveRecord::Migration\.maintain_test_schema!/m)
end
def require_rails_environment
match(/^require_relative '\.\.\/config\/environment'$/m)
end
def require_rspec_rails
match(/^require 'rspec\/rails'$/m)
end
def have_active_record_enabled
match(/^\ # config\.use_active_record = false/m)
end
def have_active_record_disabled
match(/^\ config\.use_active_record = false/m)
end
def have_transactional_fixtures_enabled
match(/^ config\.use_transactional_fixtures = true/m)
end
def filter_rails_from_backtrace
match(/config\.filter_rails_from_backtrace!/m)
end
setup_default_destination
let(:rails_helper) { content_for('spec/rails_helper.rb') }
let(:spec_helper) { content_for('spec/spec_helper.rb') }
let(:developmentrb) { content_for('config/environments/development.rb') }
it "generates .rspec" do
run_generator
expect(File.exist?(file('.rspec'))).to be true
end
it "generates spec/spec_helper.rb" do
generator_command_notice = / This file was generated by the `rails generate rspec:install` command./m
run_generator
expect(spec_helper).to match(generator_command_notice)
end
it "does not configure warnings in the spec/spec_helper.rb" do
run_generator
expect(spec_helper).not_to match(/\bconfig.warnings\b/m)
end
context "generates spec/rails_helper.rb" do
specify "requiring Rails environment" do
run_generator
expect(rails_helper).to require_rails_environment
end
specify "requiring rspec/rails" do
run_generator
expect(rails_helper).to require_rspec_rails
end
specify "with ActiveRecord" do
run_generator
expect(rails_helper).to have_active_record_enabled
expect(rails_helper).not_to have_active_record_disabled
end
specify "with default fixture path" do
run_generator
expect(rails_helper).to have_fixture_paths
end
specify "with transactional fixtures" do
run_generator
expect(rails_helper).to have_transactional_fixtures_enabled
end
specify "excluding rails gems from the backtrace" do
run_generator
expect(rails_helper).to filter_rails_from_backtrace
end
specify "checking for maintaining the schema" do
run_generator
expect(rails_helper).to maintain_test_schema
end
end
context "generates spec/rails_helper.rb", "without ActiveRecord available" do
before do
hide_const("ActiveRecord")
end
specify "requiring Rails environment" do
run_generator
expect(rails_helper).to require_rails_environment
end
specify "requiring rspec/rails" do
run_generator
expect(rails_helper).to require_rspec_rails
end
specify "without ActiveRecord" do
run_generator
expect(rails_helper).not_to have_active_record_enabled
expect(rails_helper).to have_active_record_disabled
end
specify "without fixture path" do
run_generator
expect(rails_helper).not_to have_a_fixture_path
expect(rails_helper).not_to have_fixture_paths
end
specify "without transactional fixtures" do
run_generator
expect(rails_helper).not_to have_transactional_fixtures_enabled
end
specify "without schema maintenance checks" do
run_generator
expect(rails_helper).not_to use_active_record_migration
expect(rails_helper).not_to maintain_test_schema
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec-rails.rb | lib/rspec-rails.rb | require 'rspec/rails/feature_check'
# Namespace for all core RSpec projects.
module RSpec
# Namespace for rspec-rails code.
module Rails
# Railtie to hook into Rails.
class Railtie < ::Rails::Railtie
# As of Rails 5.1.0 you can register directories to work with `rake notes`
require 'rails/source_annotation_extractor'
::Rails::SourceAnnotationExtractor::Annotation.register_directories("spec")
# As of Rails 8.0.0 you can register directories to work with `rails stats`
if ::Rails::VERSION::STRING >= "8.0.0"
require 'rails/code_statistics'
dirs = Dir['./spec/**/*_spec.rb']
.map { |f| f.sub(/^\.\/(spec\/\w+)\/.*/, '\\1') }
.uniq
.select { |f| File.directory?(f) }
Hash[dirs.map { |d| [d.split('/').last, d] }].each do |type, dir|
name = type.singularize.capitalize
::Rails::CodeStatistics.register_directory "#{name} specs", dir, test_directory: true
end
end
generators = config.app_generators
generators.integration_tool :rspec
generators.test_framework :rspec
generators do
::Rails::Generators.hidden_namespaces.reject! { |namespace| namespace.to_s.start_with?("rspec") }
end
rake_tasks do
load "rspec/rails/tasks/rspec.rake"
end
# This is called after the environment has been loaded but before Rails
# sets the default for the `preview_path`
initializer "rspec_rails.action_mailer",
before: "action_mailer.set_configs" do |app|
setup_preview_path(app)
end
private
def setup_preview_path(app)
return unless supports_action_mailer_previews?(app.config)
options = app.config.action_mailer
config_default_preview_path(options) if config_preview_path?(options)
end
def config_preview_path?(options)
# We cannot use `respond_to?(:show_previews)` here as it will always
# return `true`.
if options.show_previews.nil?
options.show_previews = ::Rails.env.development?
else
options.show_previews
end
end
def config_default_preview_path(options)
return unless options.preview_paths.empty?
options.preview_paths << "#{::Rails.root}/spec/mailers/previews"
end
def supports_action_mailer_previews?(config)
# These checks avoid loading `ActionMailer`. Using `defined?` has the
# side-effect of the class getting loaded if it is available. This is
# problematic because loading `ActionMailer::Base` will cause it to
# read the config settings; this is the only time the config is read.
# If the config is loaded now, any settings declared in a config block
# in an initializer will be ignored.
#
# If the action mailer railtie has not been loaded then `config` will
# not respond to the method. However, we cannot use
# `config.action_mailer.respond_to?(:preview_path)` here as it will
# always return `true`.
config.respond_to?(:action_mailer)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails.rb | lib/rspec/rails.rb | require 'rspec/core'
require 'rails/version'
# Load any of our adapters and extensions early in the process
require 'rspec/rails/adapters'
require 'rspec/rails/extensions'
# Load the rspec-rails parts
require 'rspec/rails/view_rendering'
require 'rspec/rails/matchers'
require 'rspec/rails/fixture_support'
require 'rspec/rails/file_fixture_support'
require 'rspec/rails/fixture_file_upload_support'
require 'rspec/rails/example'
require 'rspec/rails/vendor/capybara'
require 'rspec/rails/configuration'
require 'rspec/rails/active_record'
require 'rspec/rails/feature_check'
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/active_record.rb | lib/rspec/rails/active_record.rb | module RSpec
module Rails
# Fake class to document RSpec ActiveRecord configuration options. In practice,
# these are dynamically added to the normal RSpec configuration object.
class ActiveRecordConfiguration
# @private
def self.initialize_activerecord_configuration(config)
config.before :suite do
# This allows dynamic columns etc to be used on ActiveRecord models when creating instance_doubles
if defined?(ActiveRecord) && defined?(ActiveRecord::Base) && defined?(::RSpec::Mocks) && (::RSpec::Mocks.respond_to?(:configuration))
::RSpec::Mocks.configuration.when_declaring_verifying_double do |possible_model|
target = possible_model.target
if Class === target && ActiveRecord::Base > target && !target.abstract_class?
target.define_attribute_methods
end
end
end
end
end
initialize_activerecord_configuration RSpec.configuration
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/version.rb | lib/rspec/rails/version.rb | module RSpec
module Rails
# Version information for RSpec Rails.
module Version
# Current version of RSpec Rails, in semantic versioning format.
STRING = '8.1.0.pre'
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers.rb | lib/rspec/rails/matchers.rb | require 'rspec/core/warnings'
require 'rspec/expectations'
require 'rspec/rails/feature_check'
module RSpec
module Rails
# @api public
# Container module for Rails specific matchers.
module Matchers
end
end
end
require 'rspec/rails/matchers/base_matcher'
require 'rspec/rails/matchers/have_rendered'
require 'rspec/rails/matchers/redirect_to'
require 'rspec/rails/matchers/routing_matchers'
require 'rspec/rails/matchers/be_new_record'
require 'rspec/rails/matchers/be_a_new'
require 'rspec/rails/matchers/relation_match_array'
require 'rspec/rails/matchers/be_valid'
require 'rspec/rails/matchers/have_http_status'
require 'rspec/rails/matchers/send_email'
if RSpec::Rails::FeatureCheck.has_active_job?
require 'rspec/rails/matchers/active_job'
require 'rspec/rails/matchers/have_enqueued_mail'
end
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
require 'rspec/rails/matchers/action_cable'
end
if RSpec::Rails::FeatureCheck.has_action_mailbox?
require 'rspec/rails/matchers/action_mailbox'
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/extensions.rb | lib/rspec/rails/extensions.rb | require 'rspec/rails/extensions/active_record/proxy'
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/feature_check.rb | lib/rspec/rails/feature_check.rb | module RSpec
module Rails
# @private
module FeatureCheck
module_function
def has_active_job?
defined?(::ActiveJob)
end
def has_active_record?
defined?(::ActiveRecord)
end
def has_active_record_migration?
has_active_record? && defined?(::ActiveRecord::Migration)
end
def has_action_mailer?
defined?(::ActionMailer)
end
def has_action_mailer_preview?
has_action_mailer? && defined?(::ActionMailer::Preview)
end
def has_action_cable_testing?
defined?(::ActionCable)
end
def has_action_mailer_parameterized?
has_action_mailer? && defined?(::ActionMailer::Parameterized::DeliveryJob)
end
def has_action_mailer_unified_delivery?
has_action_mailer? && defined?(::ActionMailer::MailDeliveryJob)
end
def has_action_mailer_legacy_delivery_job?
defined?(ActionMailer::DeliveryJob)
end
def has_action_mailbox?
defined?(::ActionMailbox)
end
def type_metatag(type)
"type: :#{type}"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/view_spec_methods.rb | lib/rspec/rails/view_spec_methods.rb | module RSpec
module Rails
# Adds methods (generally to ActionView::TestCase::TestController).
# Intended for use in view specs.
module ViewSpecMethods
module_function
# Adds methods `extra_params=` and `extra_params` to the indicated class.
# When class is `::ActionView::TestCase::TestController`, these methods
# are exposed in view specs on the `controller` object.
def add_to(klass)
return if klass.method_defined?(:extra_params) && klass.method_defined?(:extra_params=)
klass.module_exec do
# Set any extra parameters that rendering a URL for this view
# would require.
#
# @example
#
# # In "spec/views/widgets/show.html.erb_spec.rb":
# before do
# widget = Widget.create!(:name => "slicer")
# controller.extra_params = { :id => widget.id }
# end
def extra_params=(hash)
@extra_params = hash
request.path =
ViewPathBuilder.new(::Rails.application.routes).path_for(
extra_params.merge(request.path_parameters)
)
end
# Use to read extra parameters that are set in the view spec.
#
# @example
#
# # After the before in the above example:
# controller.extra_params
# # => { :id => 4 }
def extra_params
@extra_params ||= {}
@extra_params.dup.freeze
end
end
end
# Removes methods `extra_params=` and `extra_params` from the indicated class.
def remove_from(klass)
klass.module_exec do
undef extra_params= if klass.method_defined?(:extra_params=)
undef extra_params if klass.method_defined?(:extra_params)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/fixture_support.rb | lib/rspec/rails/fixture_support.rb | module RSpec
module Rails
# @private
module FixtureSupport
if defined?(ActiveRecord::TestFixtures)
extend ActiveSupport::Concern
include RSpec::Rails::SetupAndTeardownAdapter
include RSpec::Rails::MinitestLifecycleAdapter
include RSpec::Rails::MinitestAssertionAdapter
include ActiveRecord::TestFixtures
# @private prevent ActiveSupport::TestFixtures to start a DB transaction.
# Monkey patched to avoid collisions with 'let(:name)' since Rails 6.1
def run_in_transaction?
current_example_name = (RSpec.current_example && RSpec.current_example.metadata[:description])
use_transactional_tests && !self.class.uses_transaction?(current_example_name)
end
included do
if RSpec.configuration.use_active_record?
include Fixtures
self.fixture_paths = RSpec.configuration.fixture_paths
self.use_transactional_tests = RSpec.configuration.use_transactional_fixtures
self.use_instantiated_fixtures = RSpec.configuration.use_instantiated_fixtures
fixtures RSpec.configuration.global_fixtures if RSpec.configuration.global_fixtures
end
end
module Fixtures
extend ActiveSupport::Concern
class_methods do
def fixtures(*args)
super.tap do
fixture_sets.each_pair do |method_name, fixture_name|
proxy_method_warning_if_called_in_before_context_scope(method_name, fixture_name)
end
end
end
def proxy_method_warning_if_called_in_before_context_scope(method_name, fixture_name)
define_method(method_name) do |*args, **kwargs, &blk|
if RSpec.current_scope == :before_context_hook
RSpec.warn_with("Calling fixture method in before :context ")
else
access_fixture(fixture_name, *args, **kwargs, &blk)
end
end
end
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/configuration.rb | lib/rspec/rails/configuration.rb | module RSpec
module Rails
# Fake class to document RSpec Rails configuration options. In practice,
# these are dynamically added to the normal RSpec configuration object.
class Configuration
# @!method infer_spec_type_from_file_location!
# Automatically tag specs in conventional directories with matching `type`
# metadata so that they have relevant helpers available to them. See
# `RSpec::Rails::DIRECTORY_MAPPINGS` for details on which metadata is
# applied to each directory.
# @!method render_views=(val)
#
# When set to `true`, controller specs will render the relevant view as
# well. Defaults to `false`.
# @!method render_views(val)
# Enables view rendering for controllers specs.
# @!method render_views?
# Reader for currently value of `render_views` setting.
end
# Mappings used by `infer_spec_type_from_file_location!`.
#
# @api private
DIRECTORY_MAPPINGS = {
channel: %w[spec channels],
controller: %w[spec controllers],
generator: %w[spec generator],
helper: %w[spec helpers],
job: %w[spec jobs],
mailer: %w[spec mailers],
model: %w[spec models],
request: %w[spec (requests|integration|api)],
routing: %w[spec routing],
view: %w[spec views],
feature: %w[spec features],
system: %w[spec system],
mailbox: %w[spec mailboxes]
}
# Sets up the different example group modules for the different spec types
#
# @api private
def self.add_test_type_configurations(config)
config.include RSpec::Rails::ControllerExampleGroup, type: :controller
config.include RSpec::Rails::HelperExampleGroup, type: :helper
config.include RSpec::Rails::ModelExampleGroup, type: :model
config.include RSpec::Rails::RequestExampleGroup, type: :request
config.include RSpec::Rails::RoutingExampleGroup, type: :routing
config.include RSpec::Rails::ViewExampleGroup, type: :view
config.include RSpec::Rails::FeatureExampleGroup, type: :feature
config.include RSpec::Rails::Matchers
config.include RSpec::Rails::SystemExampleGroup, type: :system
end
# @private
def self.initialize_configuration(config) # rubocop:disable Metrics/MethodLength
config.backtrace_exclusion_patterns << /vendor\//
config.backtrace_exclusion_patterns << %r{lib/rspec/rails}
# controller settings
config.add_setting :infer_base_class_for_anonymous_controllers, default: true
# fixture support
config.add_setting :use_active_record, default: true
config.add_setting :use_transactional_fixtures, alias_with: :use_transactional_examples
config.add_setting :use_instantiated_fixtures
config.add_setting :global_fixtures
config.add_setting :fixture_paths
config.include RSpec::Rails::FixtureSupport, :use_fixtures
# We'll need to create a deprecated module in order to properly report to
# gems / projects which are relying on this being loaded globally.
#
# See rspec/rspec-rails#1355 for history
#
# @deprecated Include `RSpec::Rails::RailsExampleGroup` or
# `RSpec::Rails::FixtureSupport` directly instead
config.include RSpec::Rails::FixtureSupport
config.add_setting :file_fixture_path, default: 'spec/fixtures/files'
config.include RSpec::Rails::FileFixtureSupport
# Add support for fixture_paths on fixture_file_upload
config.include RSpec::Rails::FixtureFileUploadSupport
# This allows us to expose `render_views` as a config option even though it
# breaks the convention of other options by using `render_views` as a
# command (i.e. `render_views = true`), where it would normally be used
# as a getter. This makes it easier for rspec-rails users because we use
# `render_views` directly in example groups, so this aligns the two APIs,
# but requires this workaround:
config.add_setting :rendering_views, default: false
config.instance_exec do
def render_views=(val)
self.rendering_views = val
end
def render_views
self.rendering_views = true
end
def render_views?
rendering_views?
end
def infer_spec_type_from_file_location!
DIRECTORY_MAPPINGS.each do |type, dir_parts|
escaped_path = Regexp.compile(dir_parts.join('[\\\/]') + '[\\\/]')
define_derived_metadata(file_path: escaped_path) do |metadata|
metadata[:type] ||= type
end
end
end
# Adds exclusion filters for gems included with Rails
def filter_rails_from_backtrace!
filter_gems_from_backtrace "actionmailer", "actionpack", "actionview"
filter_gems_from_backtrace "activemodel", "activerecord",
"activesupport", "activejob"
end
end
add_test_type_configurations(config)
if defined?(::Rails::Controller::Testing)
[:controller, :view, :request].each do |type|
config.include ::Rails::Controller::Testing::TestProcess, type: type
config.include ::Rails::Controller::Testing::TemplateAssertions, type: type
config.include ::Rails::Controller::Testing::Integration, type: type
end
end
if RSpec::Rails::FeatureCheck.has_action_mailer?
config.include RSpec::Rails::MailerExampleGroup, type: :mailer
config.after { ActionMailer::Base.deliveries.clear }
end
if RSpec::Rails::FeatureCheck.has_active_job?
config.include RSpec::Rails::JobExampleGroup, type: :job
end
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
config.include RSpec::Rails::ChannelExampleGroup, type: :channel
end
if RSpec::Rails::FeatureCheck.has_action_mailbox?
config.include RSpec::Rails::MailboxExampleGroup, type: :mailbox
end
end
initialize_configuration RSpec.configuration
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/view_rendering.rb | lib/rspec/rails/view_rendering.rb | require 'action_view/testing/resolvers'
module RSpec
module Rails
# @api public
# Helpers for optionally rendering views in controller specs.
module ViewRendering
extend ActiveSupport::Concern
# @!attribute [r]
# Returns the controller object instance under test.
attr_reader :controller
# @private
attr_writer :controller
private :controller=
# DSL methods
module ClassMethods
# @see RSpec::Rails::ControllerExampleGroup
def render_views(true_or_false = true)
@render_views = true_or_false
end
# @api private
def render_views?
return @render_views if defined?(@render_views)
if superclass.respond_to?(:render_views?)
superclass.render_views?
else
RSpec.configuration.render_views?
end
end
end
# @api private
def render_views?
self.class.render_views? || !controller.class.respond_to?(:view_paths)
end
# @private
class EmptyTemplateResolver
def self.build(path)
if path.is_a?(::ActionView::Resolver)
ResolverDecorator.new(path)
else
FileSystemResolver.new(path)
end
end
def self.nullify_template_rendering(templates)
templates.map do |template|
::ActionView::Template.new(
"",
template.identifier,
EmptyTemplateHandler,
virtual_path: template.virtual_path,
format: template_format(template),
locals: []
)
end
end
def self.template_format(template)
template.format
end
# Delegates all methods to the submitted resolver and for all methods
# that return a collection of `ActionView::Template` instances, return
# templates with modified source
#
# @private
class ResolverDecorator < ::ActionView::Resolver
(::ActionView::Resolver.instance_methods - Object.instance_methods).each do |method|
undef_method method
end
(::ActionView::Resolver.methods - Object.methods).each do |method|
singleton_class.undef_method method
end
def initialize(resolver)
@resolver = resolver
end
def method_missing(name, *args, &block)
result = @resolver.send(name, *args, &block)
nullify_templates(result)
end
private
def nullify_templates(collection)
return collection unless collection.is_a?(Enumerable)
return collection unless collection.all? { |element| element.is_a?(::ActionView::Template) }
EmptyTemplateResolver.nullify_template_rendering(collection)
end
end
# Delegates find_templates to the submitted path set and then returns
# templates with modified source
#
# @private
class FileSystemResolver < ::ActionView::FileSystemResolver
private
def find_templates(*args)
templates = super
EmptyTemplateResolver.nullify_template_rendering(templates)
end
end
end
# @private
class EmptyTemplateHandler
def self.call(_template, _source = nil)
::Rails.logger.info(" Template rendering was prevented by rspec-rails. Use `render_views` to verify rendered view contents if necessary.")
%("")
end
end
# Used to null out view rendering in controller specs.
#
# @private
module EmptyTemplates
def prepend_view_path(new_path)
super(_path_decorator(*new_path))
end
def append_view_path(new_path)
super(_path_decorator(*new_path))
end
private
def _path_decorator(*paths)
paths.map { |path| EmptyTemplateResolver.build(path) }
end
end
# @private
RESOLVER_CACHE = Hash.new do |hash, path|
hash[path] = EmptyTemplateResolver.build(path)
end
included do
before do
unless render_views?
@_original_path_set = controller.class.view_paths
path_set = @_original_path_set.map { |resolver| RESOLVER_CACHE[resolver] }
controller.class.view_paths = path_set
controller.extend(EmptyTemplates)
end
end
after do
controller.class.view_paths = @_original_path_set unless render_views?
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/file_fixture_support.rb | lib/rspec/rails/file_fixture_support.rb | require 'active_support/testing/file_fixtures'
module RSpec
module Rails
# @private
module FileFixtureSupport
extend ActiveSupport::Concern
include ActiveSupport::Testing::FileFixtures
included do
self.file_fixture_path = RSpec.configuration.file_fixture_path
if defined?(ActiveStorage::FixtureSet)
ActiveStorage::FixtureSet.file_fixture_path = RSpec.configuration.file_fixture_path
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/view_path_builder.rb | lib/rspec/rails/view_path_builder.rb | module RSpec
module Rails
# Builds paths for view specs using a particular route set.
class ViewPathBuilder
def initialize(route_set)
self.class.send(:include, route_set.url_helpers)
end
# Given a hash of parameters, build a view path, if possible.
# Returns nil if no path can be built from the given params.
#
# @example
# # path can be built because all required params are present in the hash
# view_path_builder = ViewPathBuilder.new(::Rails.application.routes)
# view_path_builder.path_for({ :controller => 'posts', :action => 'show', :id => '54' })
# # => "/post/54"
#
# @example
# # path cannot be built because the params are missing a required element (:id)
# view_path_builder.path_for({ :controller => 'posts', :action => 'delete' })
# # => ActionController::UrlGenerationError: No route matches {:action=>"delete", :controller=>"posts"}
def path_for(path_params)
url_for(path_params.merge(only_path: true))
rescue => e
e.message
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example.rb | lib/rspec/rails/example.rb | require 'rspec/rails/example/rails_example_group'
require 'rspec/rails/example/controller_example_group'
require 'rspec/rails/example/request_example_group'
require 'rspec/rails/example/helper_example_group'
require 'rspec/rails/example/view_example_group'
require 'rspec/rails/example/mailer_example_group'
require 'rspec/rails/example/routing_example_group'
require 'rspec/rails/example/model_example_group'
require 'rspec/rails/example/job_example_group'
require 'rspec/rails/example/feature_example_group'
require 'rspec/rails/example/system_example_group'
require 'rspec/rails/example/channel_example_group'
require 'rspec/rails/example/mailbox_example_group'
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/adapters.rb | lib/rspec/rails/adapters.rb | require 'delegate'
require 'active_support'
require 'active_support/concern'
require 'active_support/core_ext/string'
module RSpec
module Rails
# @private
def self.disable_testunit_autorun
# `Test::Unit::AutoRunner.need_auto_run=` was introduced to the test-unit
# gem in version 2.4.9. Previous to this version `Test::Unit.run=` was
# used. The implementation of test-unit included with Ruby has neither
# method.
if defined?(Test::Unit::AutoRunner.need_auto_run = ())
Test::Unit::AutoRunner.need_auto_run = false
elsif defined?(Test::Unit.run = ())
Test::Unit.run = false
end
end
private_class_method :disable_testunit_autorun
if defined?(Kernel.gem)
gem 'minitest'
else
require 'minitest'
end
require 'minitest/assertions'
# Constant aliased to either Minitest or TestUnit, depending on what is
# loaded.
Assertions = Minitest::Assertions
# @private
class AssertionDelegator < Module
def initialize(*assertion_modules)
assertion_class = Class.new(SimpleDelegator) do
include ::RSpec::Rails::Assertions
include ::RSpec::Rails::MinitestCounters
assertion_modules.each { |mod| include mod }
end
super() do
define_method :build_assertion_instance do
assertion_class.new(self)
end
def assertion_instance
@assertion_instance ||= build_assertion_instance
end
assertion_modules.each do |mod|
mod.public_instance_methods.each do |method|
next if method == :method_missing || method == "method_missing"
define_method(method.to_sym) do |*args, &block|
assertion_instance.send(method.to_sym, *args, &block)
end
end
end
end
end
end
# Adapts example groups for `Minitest::Test::LifecycleHooks`
#
# @private
module MinitestLifecycleAdapter
extend ActiveSupport::Concern
included do |group|
group.before { after_setup }
group.after { before_teardown }
group.around do |example|
before_setup
example.run
after_teardown
end
end
def before_setup
end
def after_setup
end
def before_teardown
end
def after_teardown
end
end
# @private
module MinitestCounters
attr_writer :assertions
def assertions
@assertions ||= 0
end
end
# @private
module SetupAndTeardownAdapter
extend ActiveSupport::Concern
module ClassMethods
# Wraps `setup` calls from within Rails' testing framework in `before`
# hooks.
def setup(*methods, &block)
methods.each do |method|
if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/
prepend_before { __send__ method }
else
before { __send__ method }
end
end
before(&block) if block
end
# @api private
#
# Wraps `teardown` calls from within Rails' testing framework in
# `after` hooks.
def teardown(*methods, &block)
methods.each { |method| after { __send__ method } }
after(&block) if block
end
end
def initialize(*args)
super
@example = nil
end
def method_name
@example
end
end
# @private
module MinitestAssertionAdapter
extend ActiveSupport::Concern
# @private
module ClassMethods
# Returns the names of assertion methods that we want to expose to
# examples without exposing non-assertion methods in Test::Unit or
# Minitest.
def assertion_method_names
::RSpec::Rails::Assertions
.public_instance_methods
.select do |m|
m.to_s =~ /^(assert|flunk|refute)/
end
end
def define_assertion_delegators
assertion_method_names.each do |m|
define_method(m.to_sym) do |*args, &block|
assertion_delegator.send(m.to_sym, *args, &block)
end
end
end
end
class AssertionDelegator
include ::RSpec::Rails::Assertions
include ::RSpec::Rails::MinitestCounters
end
def assertion_delegator
@assertion_delegator ||= AssertionDelegator.new
end
included do
define_assertion_delegators
end
end
# Backwards compatibility. It's unlikely that anyone is using this
# constant, but we had forgotten to mark it as `@private` earlier
#
# @private
TestUnitAssertionAdapter = MinitestAssertionAdapter
# @private
module TaggedLoggingAdapter
private
# Vendored from activesupport/lib/active_support/testing/tagged_logging.rb
# This implements the tagged_logger method where it is expected, but
# doesn't call `name` or set it up like Rails does.
def tagged_logger
@tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/view_assigns.rb | lib/rspec/rails/view_assigns.rb | module RSpec
module Rails
# Helpers for making instance variables available to views.
module ViewAssigns
# Assigns a value to an instance variable in the scope of the
# view being rendered.
#
# @example
#
# assign(:widget, stub_model(Widget))
def assign(key, value)
_encapsulated_assigns[key] = value
end
# Compat-shim for AbstractController::Rendering#view_assigns
def view_assigns
super.merge(_encapsulated_assigns)
end
private
def _encapsulated_assigns
@_encapsulated_assigns ||= {}
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/fixture_file_upload_support.rb | lib/rspec/rails/fixture_file_upload_support.rb | module RSpec
module Rails
# @private
module FixtureFileUploadSupport
delegate :fixture_file_upload, to: :rails_fixture_file_wrapper
private
# In Rails 7.0 fixture file path needs to be relative to `file_fixture_path` instead, this change
# was brought in with a deprecation warning on 6.1. In Rails 7.0 expect to rework this to remove
# the old accessor.
def rails_fixture_file_wrapper
RailsFixtureFileWrapper.file_fixture_path = nil
resolved_fixture_path =
if respond_to?(:file_fixture_path) && !file_fixture_path.nil?
file_fixture_path.to_s
else
(RSpec.configuration.fixture_paths&.first || '').to_s
end
RailsFixtureFileWrapper.file_fixture_path = File.join(resolved_fixture_path, '') unless resolved_fixture_path.strip.empty?
RailsFixtureFileWrapper.instance
end
class RailsFixtureFileWrapper
include ActionDispatch::TestProcess if defined?(ActionDispatch::TestProcess)
include ActiveSupport::Testing::FileFixtures
class << self
attr_accessor :fixture_paths
# Get instance of wrapper
def instance
@instance ||= new
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/vendor/capybara.rb | lib/rspec/rails/vendor/capybara.rb | begin
require 'capybara/rspec'
rescue LoadError
end
begin
require 'capybara/rails'
rescue LoadError
end
if defined?(Capybara)
RSpec.configure do |c|
if defined?(Capybara::DSL)
c.include Capybara::DSL, type: :feature
c.include Capybara::DSL, type: :system
end
if defined?(Capybara::RSpecMatchers)
c.include Capybara::RSpecMatchers, type: :view
c.include Capybara::RSpecMatchers, type: :helper
c.include Capybara::RSpecMatchers, type: :mailer
c.include Capybara::RSpecMatchers, type: :controller
c.include Capybara::RSpecMatchers, type: :feature
c.include Capybara::RSpecMatchers, type: :system
end
unless defined?(Capybara::RSpecMatchers) || defined?(Capybara::DSL)
c.include Capybara, type: :request
c.include Capybara, type: :controller
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/extensions/active_record/proxy.rb | lib/rspec/rails/extensions/active_record/proxy.rb | RSpec.configure do |rspec|
# Delay this in order to give users a chance to configure `expect_with`...
rspec.before(:suite) do
if defined?(RSpec::Matchers) &&
RSpec::Matchers.configuration.respond_to?(:syntax) && # RSpec 4 dropped support for monkey-patching `should` syntax
RSpec::Matchers.configuration.syntax.include?(:should) &&
defined?(ActiveRecord::Associations)
RSpec::Matchers.configuration.add_should_and_should_not_to ActiveRecord::Associations::CollectionProxy
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/routing_example_group.rb | lib/rspec/rails/example/routing_example_group.rb | module RSpec
module Rails
# @private
RoutingAssertionDelegator = RSpec::Rails::AssertionDelegator.new(
ActionDispatch::Assertions::RoutingAssertions
)
# @api public
# Container module for routing spec functionality.
module RoutingExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include RSpec::Rails::Matchers::RoutingMatchers
include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers
include RSpec::Rails::RoutingAssertionDelegator
# Class-level DSL for route specs.
module ClassMethods
# Specifies the routeset that will be used for the example group. This
# is most useful when testing Rails engines.
#
# @example
# describe MyEngine::PostsController do
# routes { MyEngine::Engine.routes }
#
# it "routes posts#index" do
# expect(:get => "/posts").to
# route_to(:controller => "my_engine/posts", :action => "index")
# end
# end
def routes
before do
self.routes = yield
end
end
end
included do
before do
self.routes = ::Rails.application.routes
end
end
# @!attribute [r]
# @private
attr_reader :routes
# @private
def routes=(routes)
@routes = routes
assertion_instance.instance_variable_set(:@routes, routes)
end
private
def method_missing(m, *args, &block)
routes.url_helpers.respond_to?(m) ? routes.url_helpers.send(m, *args) : super
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/request_example_group.rb | lib/rspec/rails/example/request_example_group.rb | module RSpec
module Rails
# @api public
# Container class for request spec functionality.
module RequestExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionDispatch::Integration::Runner
include ActionDispatch::Assertions
include RSpec::Rails::Matchers::RedirectTo
include RSpec::Rails::Matchers::RenderTemplate
include ActionController::TemplateAssertions
include ActionDispatch::IntegrationTest::Behavior
# Delegates to `Rails.application`.
def app
::Rails.application
end
included do
before do
@routes = ::Rails.application.routes
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/feature_example_group.rb | lib/rspec/rails/example/feature_example_group.rb | module RSpec
module Rails
# @api public
# Container module for routing spec functionality.
module FeatureExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
# Default host to be used in Rails route helpers if none is specified.
DEFAULT_HOST = "www.example.com"
included do
app = ::Rails.application
if app.respond_to?(:routes)
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
if respond_to?(:default_url_options)
default_url_options[:host] ||= ::RSpec::Rails::FeatureExampleGroup::DEFAULT_HOST
end
end
end
# Shim to check for presence of Capybara. Will delegate if present, raise
# if not. We assume here that in most cases `visit` will be the first
# Capybara method called in a spec.
def visit(*)
if defined?(super)
super
else
raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\""
end
end
end
end
end
unless RSpec.respond_to?(:feature)
opts = {
capybara_feature: true,
type: :feature,
skip: <<-EOT.squish
Feature specs require the Capybara (https://github.com/teamcapybara/capybara)
gem, version 2.13.0 or later.
EOT
}
RSpec.configure do |c|
c.alias_example_group_to :feature, opts
c.alias_example_to :scenario
c.alias_example_to :xscenario, skip: 'Temporarily skipped with xscenario'
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/view_example_group.rb | lib/rspec/rails/example/view_example_group.rb | require 'rspec/rails/view_assigns'
require 'rspec/rails/view_spec_methods'
require 'rspec/rails/view_path_builder'
module RSpec
module Rails
# @api public
# Container class for view spec functionality.
module ViewExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionView::TestCase::Behavior
include RSpec::Rails::ViewAssigns
include RSpec::Rails::Matchers::RenderTemplate
# @private
module StubResolverCache
def self.resolver_for(hash)
@resolvers ||= {}
@resolvers[hash] ||= ActionView::FixtureResolver.new(hash)
end
end
# @private
module ClassMethods
def _default_helper
base = metadata[:description].split('/')[0..-2].join('/')
(base.camelize + 'Helper').constantize unless base.to_s.empty?
rescue NameError
nil
end
def _default_helpers
helpers = [_default_helper].compact
helpers << ApplicationHelper if Object.const_defined?('ApplicationHelper')
helpers
end
end
# DSL exposed to view specs.
module ExampleMethods
extend ActiveSupport::Concern
included do
include ::Rails.application.routes.url_helpers
include ::Rails.application.routes.mounted_helpers
end
# @overload render
# @overload render({partial: path_to_file})
# @overload render({partial: path_to_file}, {... locals ...})
# @overload render({partial: path_to_file}, {... locals ...}) do ... end
#
# Delegates to ActionView::Base#render, so see documentation on that
# for more info.
#
# The only addition is that you can call render with no arguments, and
# RSpec will pass the top level description to render:
#
# describe "widgets/new.html.erb" do
# it "shows all the widgets" do
# render # => view.render(file: "widgets/new.html.erb")
# # ...
# end
# end
def render(options = {}, local_assigns = {}, &block)
options = _default_render_options if Hash === options && options.empty?
options = options.merge(_default_render_options) if Hash === options && options.keys == [:locals]
super(options, local_assigns, &block)
end
# The instance of `ActionView::Base` that is used to render the template.
# Use this to stub methods _before_ calling `render`.
#
# describe "widgets/new.html.erb" do
# it "shows all the widgets" do
# view.stub(:foo) { "foo" }
# render
# # ...
# end
# end
def view
_view
end
# Simulates the presence of a template on the file system by adding a
# Rails' FixtureResolver to the front of the view_paths list. Designed to
# help isolate view examples from partials rendered by the view template
# that is the subject of the example.
#
# stub_template("widgets/_widget.html.erb" => "This content.")
def stub_template(hash)
controller.prepend_view_path(StubResolverCache.resolver_for(hash))
end
# Provides access to the params hash that will be available within the
# view.
#
# params[:foo] = 'bar'
def params
controller.params
end
# @deprecated Use `view` instead.
def template
RSpec.deprecate("template", replacement: "view")
view
end
# @deprecated Use `rendered` instead.
def response
# `assert_template` expects `response` to implement a #body method
# like an `ActionDispatch::Response` does to force the view to
# render. For backwards compatibility, we use #response as an alias
# for #rendered, but it needs to implement #body to avoid
# `assert_template` raising a `NoMethodError`.
unless rendered.respond_to?(:body)
def rendered.body
self
end
end
rendered
end
private
def _default_render_options
formats = if ActionView::Template::Types.respond_to?(:symbols)
ActionView::Template::Types.symbols
else
[:html, :text, :js, :css, :xml, :json].map(&:to_s)
end.map { |x| Regexp.escape(x) }.join("|")
handlers = ActionView::Template::Handlers.extensions.map { |x| Regexp.escape(x) }.join("|")
locales = "[a-z]{2}(?:-[A-Z]{2})?"
variants = "[^.]*"
path_regex = %r{
\A
(?<template>.*?)
(?:\.(?<locale>#{locales}))??
(?:\.(?<format>#{formats}))??
(?:\+(?<variant>#{variants}))??
(?:\.(?<handler>#{handlers}))?
\z
}x
# This regex should always find a match.
# Worst case, everything will be nil, and :template will just be
# the original string.
match = path_regex.match(_default_file_to_render)
render_options = { template: match[:template] }
render_options[:handlers] = [match[:handler].to_sym] if match[:handler]
render_options[:formats] = [match[:format].to_sym] if match[:format]
render_options[:locales] = [match[:locale].to_sym] if match[:locale]
render_options[:variants] = [match[:variant].to_sym] if match[:variant]
render_options
end
def _path_parts
_default_file_to_render.split("/")
end
def _controller_path
_path_parts[0..-2].join("/")
end
def _inferred_action
_path_parts.last.split(".").first
end
def _include_controller_helpers
helpers = controller._helpers
view.singleton_class.class_exec do
include helpers unless included_modules.include?(helpers)
end
end
end
included do
include ExampleMethods
helper(*_default_helpers)
before do
_include_controller_helpers
view.lookup_context.prefixes << _controller_path
controller.controller_path = _controller_path
path_params_to_merge = {}
path_params_to_merge[:controller] = _controller_path
path_params_to_merge[:action] = _inferred_action unless _inferred_action =~ /^_/
path_params = controller.request.path_parameters
controller.request.path_parameters = path_params.reverse_merge(path_params_to_merge)
controller.request.path = ViewPathBuilder.new(::Rails.application.routes).path_for(controller.request.path_parameters)
ViewSpecMethods.add_to(::ActionView::TestCase::TestController)
end
after do
ViewSpecMethods.remove_from(::ActionView::TestCase::TestController)
end
let(:_default_file_to_render) do |example|
example.example_group.top_level_description
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/helper_example_group.rb | lib/rspec/rails/example/helper_example_group.rb | require 'rspec/rails/view_assigns'
module RSpec
module Rails
# @api public
# Container module for helper specs.
module HelperExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionView::TestCase::Behavior
include RSpec::Rails::ViewAssigns
# @private
module ClassMethods
def determine_constant_from_test_name(_ignore)
described_class if yield(described_class)
end
end
# Returns an instance of ActionView::Base with the helper being specified
# mixed in, along with any of the built-in rails helpers.
def helper
_view.tap do |v|
v.extend(ApplicationHelper) if defined?(ApplicationHelper)
v.assign(view_assigns)
end
end
private
def _controller_path(example)
example.example_group.described_class.to_s.sub(/Helper/, '').underscore
end
included do
before do |example|
controller.controller_path = _controller_path(example)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/controller_example_group.rb | lib/rspec/rails/example/controller_example_group.rb | module RSpec
module Rails
# @private
ControllerAssertionDelegator = RSpec::Rails::AssertionDelegator.new(
ActionDispatch::Assertions::RoutingAssertions
)
# @api public
# Container module for controller spec functionality.
module ControllerExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionController::TestCase::Behavior
include RSpec::Rails::ViewRendering
include RSpec::Rails::Matchers::RedirectTo
include RSpec::Rails::Matchers::RenderTemplate
include RSpec::Rails::Matchers::RoutingMatchers
include ControllerAssertionDelegator
# Class-level DSL for controller specs.
module ClassMethods
# @private
def controller_class
described_class
end
# Supports a simple DSL for specifying behavior of ApplicationController.
# Creates an anonymous subclass of ApplicationController and evals the
# `body` in that context. Also sets up implicit routes for this
# controller, that are separate from those defined in "config/routes.rb".
#
# @note Due to Ruby 1.8 scoping rules in anonymous subclasses, constants
# defined in `ApplicationController` must be fully qualified (e.g.
# `ApplicationController::AccessDenied`) in the block passed to the
# `controller` method. Any instance methods, filters, etc, that are
# defined in `ApplicationController`, however, are accessible from
# within the block.
#
# @example
# describe ApplicationController do
# controller do
# def index
# raise ApplicationController::AccessDenied
# end
# end
#
# describe "handling AccessDenied exceptions" do
# it "redirects to the /401.html page" do
# get :index
# response.should redirect_to("/401.html")
# end
# end
# end
#
# If you would like to spec a subclass of ApplicationController, call
# controller like so:
#
# controller(ApplicationControllerSubclass) do
# # ....
# end
def controller(base_class = nil, &body)
if RSpec.configuration.infer_base_class_for_anonymous_controllers?
base_class ||= controller_class
end
base_class ||= defined?(ApplicationController) ? ApplicationController : ActionController::Base
new_controller_class = Class.new(base_class) do
def self.name
root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base
if superclass == root_controller || superclass.abstract?
"AnonymousController"
else
superclass.name
end
end
end
new_controller_class.class_exec(&body)
(class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class }
before do
@orig_routes = routes
resource_name = if @controller.respond_to?(:controller_name)
@controller.controller_name.to_sym
else
:anonymous
end
resource_path = if @controller.respond_to?(:controller_path)
@controller.controller_path
else
resource_name.to_s
end
resource_module = resource_path.rpartition('/').first.presence
resource_as = 'anonymous_' + resource_path.tr('/', '_')
self.routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
r.draw do
resources resource_name,
as: resource_as,
module: resource_module,
path: resource_path
end
end
end
after do
self.routes = @orig_routes
@orig_routes = nil
end
end
# Specifies the routeset that will be used for the example group. This
# is most useful when testing Rails engines.
#
# @example
# describe MyEngine::PostsController do
# routes { MyEngine::Engine.routes }
#
# # ...
# end
def routes
before do
self.routes = yield
end
end
end
# @!attribute [r]
# Returns the controller object instance under test.
attr_reader :controller
# @!attribute [r]
# Returns the Rails routes used for the spec.
attr_reader :routes
# @private
#
# RSpec Rails uses this to make Rails routes easily available to specs.
def routes=(routes)
@routes = routes
assertion_instance.instance_variable_set(:@routes, routes)
end
# @private
module BypassRescue
def rescue_with_handler(exception)
raise exception
end
end
# Extends the controller with a module that overrides
# `rescue_with_handler` to raise the exception passed to it. Use this to
# specify that an action _should_ raise an exception given appropriate
# conditions.
#
# @example
# describe ProfilesController do
# it "raises a 403 when a non-admin user tries to view another user's profile" do
# profile = create_profile
# login_as profile.user
#
# expect do
# bypass_rescue
# get :show, id: profile.id + 1
# end.to raise_error(/403 Forbidden/)
# end
# end
def bypass_rescue
controller.extend(BypassRescue)
end
# If method is a named_route, delegates to the RouteSet associated with
# this controller.
def method_missing(method, *args, &block)
if route_available?(method)
controller.send(method, *args, &block)
else
super
end
end
ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true)
included do
subject { controller }
before do
self.routes = ::Rails.application.routes
end
around do |ex|
previous_allow_forgery_protection_value = ActionController::Base.allow_forgery_protection
begin
ActionController::Base.allow_forgery_protection = false
ex.call
ensure
ActionController::Base.allow_forgery_protection = previous_allow_forgery_protection_value
end
end
end
private
def route_available?(method)
(defined?(@routes) && route_defined?(routes, method)) ||
(defined?(@orig_routes) && route_defined?(@orig_routes, method))
end
def route_defined?(routes, method)
return false if routes.nil?
if routes.named_routes.respond_to?(:route_defined?)
routes.named_routes.route_defined?(method)
else
routes.named_routes.helpers.include?(method)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/job_example_group.rb | lib/rspec/rails/example/job_example_group.rb | module RSpec
module Rails
# @api public
# Container module for job spec functionality. It is only available if
# ActiveJob has been loaded before it.
module JobExampleGroup
# This blank module is only necessary for YARD processing. It doesn't
# handle the conditional `defined?` check below very well.
end
end
end
if defined?(ActiveJob)
module RSpec
module Rails
# Container module for job spec functionality.
module JobExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/mailer_example_group.rb | lib/rspec/rails/example/mailer_example_group.rb | module RSpec
module Rails
# @api public
# Container module for mailer spec functionality. It is only available if
# ActionMailer has been loaded before it.
module MailerExampleGroup
# This blank module is only necessary for YARD processing. It doesn't
# handle the conditional `defined?` check below very well.
end
end
end
if defined?(ActionMailer)
module RSpec
module Rails
# Container module for mailer spec functionality.
module MailerExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionMailer::TestCase::Behavior
included do
include ::Rails.application.routes.url_helpers
options = ::Rails.configuration.action_mailer.default_url_options || {}
options.each { |key, value| default_url_options[key] = value }
end
# Class-level DSL for mailer specs.
module ClassMethods
# Alias for `described_class`.
def mailer_class
described_class
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/model_example_group.rb | lib/rspec/rails/example/model_example_group.rb | module RSpec
module Rails
# @api public
# Container class for model spec functionality. Does not provide anything
# special over the common RailsExampleGroup currently.
module ModelExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/channel_example_group.rb | lib/rspec/rails/example/channel_example_group.rb | require "rspec/rails/matchers/action_cable/have_streams"
module RSpec
module Rails
# @api public
# Container module for channel spec functionality. It is only available if
# ActionCable has been loaded before it.
module ChannelExampleGroup
# @private
module ClassMethods
# These blank modules are only necessary for YARD processing. It doesn't
# handle the conditional check below very well and reports undocumented objects.
end
end
end
end
if RSpec::Rails::FeatureCheck.has_action_cable_testing?
module RSpec
module Rails
# @api public
# Container module for channel spec functionality.
module ChannelExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include ActionCable::Connection::TestCase::Behavior
include ActionCable::Channel::TestCase::Behavior
# Class-level DSL for channel specs.
module ClassMethods
# @private
def channel_class
(_channel_class || described_class).tap do |klass|
next if klass <= ::ActionCable::Channel::Base
raise "Described class is not a channel class.\n" \
"Specify the channel class in the `describe` statement " \
"or set it manually using `tests MyChannelClass`"
end
end
# @private
def connection_class
(_connection_class || described_class).tap do |klass|
next if klass <= ::ActionCable::Connection::Base
raise "Described class is not a connection class.\n" \
"Specify the connection class in the `describe` statement " \
"or set it manually using `tests MyConnectionClass`"
end
end
end
# Checks that the connection attempt has been rejected.
#
# @example
# expect { connect }.to have_rejected_connection
def have_rejected_connection
raise_error(::ActionCable::Connection::Authorization::UnauthorizedError)
end
# Checks that the subscription is subscribed to at least one stream.
#
# @example
# expect(subscription).to have_streams
def have_streams
check_subscribed!
RSpec::Rails::Matchers::ActionCable::HaveStream.new
end
# Checks that the channel has been subscribed to the given stream
#
# @example
# expect(subscription).to have_stream_from("chat_1")
def have_stream_from(stream)
check_subscribed!
RSpec::Rails::Matchers::ActionCable::HaveStream.new(stream)
end
# Checks that the channel has been subscribed to a stream for the given model
#
# @example
# expect(subscription).to have_stream_for(user)
def have_stream_for(object)
check_subscribed!
RSpec::Rails::Matchers::ActionCable::HaveStream.new(broadcasting_for(object))
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/mailbox_example_group.rb | lib/rspec/rails/example/mailbox_example_group.rb | module RSpec
module Rails
# @api public
# Container module for mailbox spec functionality.
module MailboxExampleGroup
extend ActiveSupport::Concern
if RSpec::Rails::FeatureCheck.has_action_mailbox?
require 'action_mailbox/test_helper'
extend ::ActionMailbox::TestHelper
# @private
def self.create_inbound_email(arg)
case arg
when Hash
create_inbound_email_from_mail(**arg)
else
create_inbound_email_from_source(arg.to_s)
end
end
else
def self.create_inbound_email(_arg)
raise "Could not load ActionMailer::TestHelper"
end
end
class_methods do
# @private
def mailbox_class
described_class
end
end
included do
subject { described_class }
end
# @api public
# Passes if the inbound email was delivered
#
# @example
# inbound_email = process(args)
# expect(inbound_email).to have_been_delivered
def have_been_delivered
satisfy('have been delivered', &:delivered?)
end
# @api public
# Passes if the inbound email bounced during processing
#
# @example
# inbound_email = process(args)
# expect(inbound_email).to have_bounced
def have_bounced
satisfy('have bounced', &:bounced?)
end
# @api public
# Passes if the inbound email failed to process
#
# @example
# inbound_email = process(args)
# expect(inbound_email).to have_failed
def have_failed
satisfy('have failed', &:failed?)
end
# Process an inbound email message directly, bypassing routing.
#
# @param message [Hash, Mail::Message] a mail message or hash of
# attributes used to build one
# @return [ActionMailbox::InboundMessage]
def process(message)
MailboxExampleGroup.create_inbound_email(message).tap do |mail|
self.class.mailbox_class.receive(mail)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/rails_example_group.rb | lib/rspec/rails/example/rails_example_group.rb | # Temporary workaround to resolve circular dependency between rspec-rails' spec
# suite and ammeter.
require 'rspec/rails/matchers'
require 'active_support/current_attributes/test_helper'
require 'active_support/execution_context/test_helper'
module RSpec
module Rails
# @api public
# Common rails example functionality.
module RailsExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::SetupAndTeardownAdapter
include RSpec::Rails::MinitestLifecycleAdapter
include RSpec::Rails::MinitestAssertionAdapter
include RSpec::Rails::FixtureSupport
include RSpec::Rails::TaggedLoggingAdapter
include ActiveSupport::CurrentAttributes::TestHelper
include ActiveSupport::ExecutionContext::TestHelper
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/example/system_example_group.rb | lib/rspec/rails/example/system_example_group.rb | module RSpec
module Rails
# @api public
# Container class for system tests
module SystemExampleGroup
extend ActiveSupport::Concern
include RSpec::Rails::RailsExampleGroup
include RSpec::Rails::Matchers::RedirectTo
include RSpec::Rails::Matchers::RenderTemplate
include ActionDispatch::Integration::Runner
include ActionDispatch::Assertions
include ActionController::TemplateAssertions
# Special characters to translate into underscores for #method_name
CHARS_TO_TRANSLATE = ['/', '.', ':', ',', "'", '"', " "].freeze
# @private
module BlowAwayTeardownHooks
# @private
def before_teardown
end
# @private
def after_teardown
end
end
# for the SystemTesting Screenshot situation
def passed?
return false if RSpec.current_example.exception
return true unless defined?(::RSpec::Expectations::FailureAggregator)
failure_notifier = ::RSpec::Support.failure_notifier
return true unless failure_notifier.is_a?(::RSpec::Expectations::FailureAggregator)
failure_notifier.failures.empty? && failure_notifier.other_errors.empty?
end
# @private
def method_name
@method_name ||= [
self.class.name.underscore,
RSpec.current_example.description.underscore
].join("_").tr(CHARS_TO_TRANSLATE.join, "_").byteslice(0...200).scrub("") + "_#{rand(1000)}"
end
# @private
# Allows failure screenshot to work whilst not exposing metadata
class SuppressRailsScreenshotMetadata
def initialize
@example_data = {}
end
def [](key)
if @example_data.key?(key)
@example_data[key]
else
raise_wrong_scope_error
end
end
def []=(key, value)
if key == :failure_screenshot_path
@example_data[key] = value
else
raise_wrong_scope_error
end
end
def method_missing(_name, *_args, &_block)
raise_wrong_scope_error
end
private
def raise_wrong_scope_error
raise RSpec::Core::ExampleGroup::WrongScopeError,
"`metadata` is not available from within an example " \
"(e.g. an `it` block) or from constructs that run in the " \
"scope of an example (e.g. `before`, `let`, etc). It is " \
"only available on an example group (e.g. a `describe` or "\
"`context` block)"
end
end
# @private
def metadata
@metadata ||= SuppressRailsScreenshotMetadata.new
end
# Delegates to `Rails.application`.
def app
::Rails.application
end
# Default driver to assign if none specified.
DEFAULT_DRIVER = :selenium_chrome_headless
included do |other|
ActiveSupport.on_load(:action_dispatch_system_test_case) do
ActionDispatch::SystemTesting::Server.silence_puma = true
end
require 'action_dispatch/system_test_case'
begin
require 'capybara'
rescue LoadError => e
abort """
LoadError: #{e.message}
System test integration has a hard
dependency on a webserver and `capybara`, please add capybara to
your Gemfile and configure a webserver (e.g. `Capybara.server =
:puma`) before attempting to use system specs.
""".gsub(/\s+/, ' ').strip
end
original_before_teardown =
::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown.instance_method(:before_teardown)
original_after_teardown =
::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown.instance_method(:after_teardown)
other.include ::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown
other.include ::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper
other.include BlowAwayTeardownHooks
attr_reader :driver
if ActionDispatch::SystemTesting::Server.respond_to?(:silence_puma=)
ActionDispatch::SystemTesting::Server.silence_puma = true
end
def initialize(*args, &blk)
super(*args, &blk)
@driver = nil
self.class.before do
# A user may have already set the driver, so only default if driver
# is not set
driven_by(DEFAULT_DRIVER) unless @driver
end
end
def driven_by(driver, **driver_options, &blk)
@driver = ::ActionDispatch::SystemTestCase.driven_by(driver, **driver_options, &blk).tap(&:use)
end
def served_by(**options)
::ActionDispatch::SystemTestCase.served_by(**options)
end
before do
@routes = ::Rails.application.routes
end
after do
orig_stdout = $stdout
$stdout = StringIO.new
begin
original_before_teardown.bind(self).call
ensure
myio = $stdout
myio.rewind
RSpec.current_example.metadata[:extra_failure_lines] = myio.readlines
$stdout = orig_stdout
end
end
around do |example|
example.run
original_after_teardown.bind(self).call
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/base_matcher.rb | lib/rspec/rails/matchers/base_matcher.rb | module RSpec
module Rails
module Matchers
# @api private
#
# Base class to build matchers. Should not be instantiated directly.
class BaseMatcher
include RSpec::Matchers::Composable
# @api private
# Used to detect when no arg is passed to `initialize`.
# `nil` cannot be used because it's a valid value to pass.
UNDEFINED = Object.new.freeze
# @private
attr_reader :actual, :expected, :rescued_exception
# @private
attr_writer :matcher_name
def initialize(expected = UNDEFINED)
@expected = expected unless UNDEFINED.equal?(expected)
end
# @api private
# Indicates if the match is successful. Delegates to `match`, which
# should be defined on a subclass. Takes care of consistently
# initializing the `actual` attribute.
def matches?(actual)
@actual = actual
match(expected, actual)
end
# @api private
# Used to wrap a block of code that will indicate failure by
# raising one of the named exceptions.
#
# This is used by rspec-rails for some of its matchers that
# wrap rails' assertions.
def match_unless_raises(*exceptions)
exceptions.unshift Exception if exceptions.empty?
begin
yield
true
rescue *exceptions => @rescued_exception
false
end
end
# @api private
# Generates a description using {RSpec::Matchers::EnglishPhrasing}.
# @return [String]
def description
desc = RSpec::Matchers::EnglishPhrasing.split_words(self.class.matcher_name)
desc << RSpec::Matchers::EnglishPhrasing.list(@expected) if defined?(@expected)
desc
end
# @api private
# Matchers are not diffable by default. Override this to make your
# subclass diffable.
def diffable?
false
end
# @api private
# Most matchers are value matchers (i.e. meant to work with `expect(value)`)
# rather than block matchers (i.e. meant to work with `expect { }`), so
# this defaults to false. Block matchers must override this to return true.
def supports_block_expectations?
false
end
# @api private
def expects_call_stack_jump?
false
end
# @private
def expected_formatted
RSpec::Support::ObjectFormatter.format(@expected)
end
# @private
def actual_formatted
RSpec::Support::ObjectFormatter.format(@actual)
end
# @private
def self.matcher_name
@matcher_name ||= underscore(name.split('::').last)
end
# @private
def matcher_name
if defined?(@matcher_name)
@matcher_name
else
self.class.matcher_name
end
end
# @private
# Borrowed from ActiveSupport.
def self.underscore(camel_cased_word)
word = camel_cased_word.to_s.dup
word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
word.tr!('-', '_')
word.downcase!
word
end
private_class_method :underscore
private
def assert_ivars(*expected_ivars)
return unless (expected_ivars - present_ivars).any?
ivar_list = RSpec::Matchers::EnglishPhrasing.list(expected_ivars)
raise "#{self.class.name} needs to supply#{ivar_list}"
end
alias present_ivars instance_variables
# @private
module HashFormatting
# `{ :a => 5, :b => 2 }.inspect` produces:
#
# {:a=>5, :b=>2}
#
# ...but it looks much better as:
#
# {:a => 5, :b => 2}
#
# This is idempotent and safe to run on a string multiple times.
def improve_hash_formatting(inspect_string)
inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2')
end
module_function :improve_hash_formatting
end
include HashFormatting
# @api private
# Provides default implementations of failure messages, based on the `description`.
module DefaultFailureMessages
# @api private
# Provides a good generic failure message. Based on `description`.
# When subclassing, if you are not satisfied with this failure message
# you often only need to override `description`.
# @return [String]
def failure_message
"expected #{description_of @actual} to #{description}".dup
end
# @api private
# Provides a good generic negative failure message. Based on `description`.
# When subclassing, if you are not satisfied with this failure message
# you often only need to override `description`.
# @return [String]
def failure_message_when_negated
"expected #{description_of @actual} not to #{description}".dup
end
# @private
def self.has_default_failure_messages?(matcher)
matcher.method(:failure_message).owner == self &&
matcher.method(:failure_message_when_negated).owner == self
rescue NameError
false
end
end
include DefaultFailureMessages
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/have_enqueued_mail.rb | lib/rspec/rails/matchers/have_enqueued_mail.rb | # We require the minimum amount of rspec-mocks possible to avoid
# conflicts with other mocking frameworks.
# See: https://github.com/rspec/rspec-rails/issues/2252
require "rspec/mocks/argument_matchers"
require "rspec/rails/matchers/active_job"
# rubocop: disable Metrics/ClassLength
module RSpec
module Rails
module Matchers
# Matcher class for `have_enqueued_mail`. Should not be instantiated directly.
#
# @private
# @see RSpec::Rails::Matchers#have_enqueued_mail
class HaveEnqueuedMail < ActiveJob::HaveEnqueuedJob
MAILER_JOB_METHOD = 'deliver_now'.freeze
include RSpec::Mocks::ArgumentMatchers
def initialize(mailer_class, method_name)
super(nil)
@mailer_class = mailer_class
@method_name = method_name
@mail_args = []
end
def description
"enqueues #{mailer_class_name}.#{@method_name}"
end
def with(*args, &block)
@mail_args = args
block.nil? ? super : super(&yield_mail_args(block))
end
def matches?(block)
raise ArgumentError, 'have_enqueued_mail and enqueue_mail only work with block arguments' unless block.respond_to?(:call)
check_active_job_adapter
super
end
def failure_message
return @failure_message if defined?(@failure_message)
"expected to enqueue #{base_message}".tap do |msg|
msg << "\n#{unmatching_mail_jobs_message}" if unmatching_mail_jobs.any?
end
end
def failure_message_when_negated
"expected not to enqueue #{base_message}"
end
private
def base_message
[mailer_class_name, @method_name].compact.join('.').tap do |msg|
msg << " #{expected_count_message}"
msg << " with #{@mail_args}," if @mail_args.any?
msg << " on queue #{@queue}," if @queue
msg << " at #{@at.inspect}," if @at
msg << " but enqueued #{@matching_jobs.size}"
end
end
def expected_count_message
"#{message_expectation_modifier} #{@expected_number} #{@expected_number == 1 ? 'time' : 'times'}"
end
def mailer_class_name
@mailer_class ? @mailer_class.name : 'ActionMailer::Base'
end
def job_matches?(job)
legacy_mail?(job) || parameterized_mail?(job) || unified_mail?(job)
end
def arguments_match?(job)
@args =
if @mail_args.any?
base_mailer_args + @mail_args
elsif @mailer_class && @method_name
base_mailer_args + [any_args]
elsif @mailer_class
[mailer_class_name, any_args]
else
[]
end
super(job)
end
def detect_args_signature_mismatch(jobs)
return if @method_name.nil?
return if skip_signature_verification?
mailer_class = mailer_class_name.constantize
jobs.each do |job|
mailer_args = extract_args_without_parameterized_params(job)
if (signature_mismatch = check_args_signature_mismatch(mailer_class, @method_name, mailer_args))
return signature_mismatch
end
end
nil
end
def base_mailer_args
[mailer_class_name, @method_name.to_s, MAILER_JOB_METHOD]
end
def yield_mail_args(block)
proc { |*job_args| block.call(*(job_args - base_mailer_args)) }
end
def check_active_job_adapter
return if ::ActiveJob::QueueAdapters::TestAdapter === ::ActiveJob::Base.queue_adapter
raise StandardError, "To use HaveEnqueuedMail matcher set `ActiveJob::Base.queue_adapter = :test`"
end
def unmatching_mail_jobs
@unmatching_jobs.select do |job|
job_matches?(job)
end
end
def unmatching_mail_jobs_message
messages = ["Queued deliveries:"]
unmatching_mail_jobs.each do |job|
messages << " #{mail_job_message(job)}"
end
messages.join("\n")
end
def mail_job_message(job)
job_args = deserialize_arguments(job)
mailer_method = job_args[0..1].join('.')
mailer_args = job_args[3..-1]
msg_parts = []
msg_parts << "with #{mailer_args}" if mailer_args.any?
msg_parts << "on queue #{job[:queue]}" if job[:queue] && job[:queue] != 'mailers'
msg_parts << "at #{Time.at(job[:at])}" if job[:at]
"#{mailer_method} #{msg_parts.join(', ')}".strip
end
# Ruby 3.1 changed how params were serialized on Rails 6.1
# so we override the active job implementation and customize it here.
def deserialize_arguments(job)
args = super
return args unless Hash === args.last
hash = args.pop
if hash.key?("_aj_ruby2_keywords")
keywords = hash["_aj_ruby2_keywords"]
original_hash = keywords.each_with_object({}) { |keyword, new_hash| new_hash[keyword.to_sym] = hash[keyword] }
args + [original_hash]
elsif hash.key?(:args) && hash.key?(:params)
args + [hash]
elsif hash.key?(:args)
args + hash[:args]
else
args + [hash]
end
end
def extract_args_without_parameterized_params(job)
args = deserialize_arguments(job)
mailer_args = args - base_mailer_args
if parameterized_mail?(job)
mailer_args = mailer_args[1..-1] # ignore parameterized params
elsif mailer_args.last.is_a?(Hash) && mailer_args.last.key?(:args)
mailer_args = args.last[:args]
end
mailer_args
end
def legacy_mail?(job)
RSpec::Rails::FeatureCheck.has_action_mailer_legacy_delivery_job? && job[:job] <= ActionMailer::DeliveryJob
end
def parameterized_mail?(job)
RSpec::Rails::FeatureCheck.has_action_mailer_parameterized? && job[:job] <= ActionMailer::Parameterized::DeliveryJob
end
def unified_mail?(job)
RSpec::Rails::FeatureCheck.has_action_mailer_unified_delivery? && job[:job] <= ActionMailer::MailDeliveryJob
end
end
# @api public
# Passes if an email has been enqueued inside block.
# May chain with to specify expected arguments.
# May chain at_least, at_most or exactly to specify a number of times.
# May chain at to specify a send time.
# May chain on_queue to specify a queue.
#
# @example
# expect {
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail
#
# expect {
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail(MyMailer)
#
# expect {
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail(MyMailer, :welcome)
#
# # Using alias
# expect {
# MyMailer.welcome(user).deliver_later
# }.to enqueue_mail(MyMailer, :welcome)
#
# expect {
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail(MyMailer, :welcome).with(user)
#
# expect {
# MyMailer.welcome(user).deliver_later
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail(MyMailer, :welcome).at_least(:once)
#
# expect {
# MyMailer.welcome(user).deliver_later
# }.to have_enqueued_mail(MyMailer, :welcome).at_most(:twice)
#
# expect {
# MyMailer.welcome(user).deliver_later(wait_until: Date.tomorrow.noon)
# }.to have_enqueued_mail(MyMailer, :welcome).at(Date.tomorrow.noon)
#
# expect {
# MyMailer.welcome(user).deliver_later(queue: :urgent_mail)
# }.to have_enqueued_mail(MyMailer, :welcome).on_queue(:urgent_mail)
def have_enqueued_mail(mailer_class = nil, mail_method_name = nil)
HaveEnqueuedMail.new(mailer_class, mail_method_name)
end
alias_method :have_enqueued_email, :have_enqueued_mail
alias_method :enqueue_mail, :have_enqueued_mail
alias_method :enqueue_email, :have_enqueued_mail
end
end
end
# rubocop: enable Metrics/ClassLength
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/active_job.rb | lib/rspec/rails/matchers/active_job.rb | require "active_job/base"
require "active_job/arguments"
module RSpec
module Rails
module Matchers
# Namespace for various implementations of ActiveJob features
#
# @api private
module ActiveJob
# rubocop: disable Metrics/ClassLength
# @private
class Base < RSpec::Rails::Matchers::BaseMatcher
def initialize
@args = []
@queue = nil
@priority = nil
@at = nil
@block = proc { }
set_expected_number(:exactly, 1)
end
def with(*args, &block)
@args = args
@block = block if block.present?
self
end
def on_queue(queue)
@queue = queue.to_s
self
end
def at_priority(priority)
@priority = priority.to_i
self
end
def at(time_or_date)
case time_or_date
when Time then @at = Time.at(time_or_date.to_f)
else
@at = time_or_date
end
self
end
def exactly(count)
set_expected_number(:exactly, count)
self
end
def at_least(count)
set_expected_number(:at_least, count)
self
end
def at_most(count)
set_expected_number(:at_most, count)
self
end
def times
self
end
def once
exactly(:once)
end
def twice
exactly(:twice)
end
def thrice
exactly(:thrice)
end
def failure_message
return @failure_message if defined?(@failure_message)
"expected to #{self.class::FAILURE_MESSAGE_EXPECTATION_ACTION} #{base_message}".tap do |msg|
if @unmatching_jobs.any?
msg << "\nQueued jobs:"
@unmatching_jobs.each do |job|
msg << "\n #{base_job_message(job)}"
end
end
end
end
def failure_message_when_negated
"expected not to #{self.class::FAILURE_MESSAGE_EXPECTATION_ACTION} #{base_message}"
end
def message_expectation_modifier
case @expectation_type
when :exactly then "exactly"
when :at_most then "at most"
when :at_least then "at least"
end
end
def supports_block_expectations?
true
end
private
def check(jobs)
@matching_jobs, @unmatching_jobs = jobs.partition do |job|
if matches_constraints?(job)
args = deserialize_arguments(job)
@block.call(*args)
true
else
false
end
end
if (signature_mismatch = detect_args_signature_mismatch(@matching_jobs))
@failure_message = signature_mismatch
return false
end
@matching_jobs_count = @matching_jobs.size
case @expectation_type
when :exactly then @expected_number == @matching_jobs_count
when :at_most then @expected_number >= @matching_jobs_count
when :at_least then @expected_number <= @matching_jobs_count
end
end
def base_message
"#{message_expectation_modifier} #{@expected_number} jobs,".tap do |msg|
msg << " with #{@args}," if @args.any?
msg << " on queue #{@queue}," if @queue
msg << " at #{@at.inspect}," if @at
msg << " with priority #{@priority}," if @priority
msg << " but #{self.class::MESSAGE_EXPECTATION_ACTION} #{@matching_jobs_count}"
end
end
def base_job_message(job)
msg_parts = []
msg_parts << "with #{deserialize_arguments(job)}" if job[:args].any?
msg_parts << "on queue #{job[:queue]}" if job[:queue]
msg_parts << "at #{Time.at(job[:at])}" if job[:at]
msg_parts <<
if job[:priority]
"with priority #{job[:priority]}"
else
"with no priority specified"
end
"#{job[:job].name} job".tap do |msg|
msg << " #{msg_parts.join(', ')}" if msg_parts.any?
end
end
def matches_constraints?(job)
job_matches?(job) && arguments_match?(job) && queue_match?(job) && at_match?(job) && priority_match?(job)
end
def job_matches?(job)
@job ? @job == job[:job] : true
end
def arguments_match?(job)
if @args.any?
args = serialize_and_deserialize_arguments(@args)
deserialized_args = deserialize_arguments(job)
RSpec::Mocks::ArgumentListMatcher.new(*args).args_match?(*deserialized_args)
else
true
end
end
def detect_args_signature_mismatch(jobs)
return if skip_signature_verification?
jobs.each do |job|
args = deserialize_arguments(job)
if (signature_mismatch = check_args_signature_mismatch(job.fetch(:job), :perform, args))
return signature_mismatch
end
end
nil
end
def skip_signature_verification?
return true unless defined?(::RSpec::Mocks) && (::RSpec::Mocks.respond_to?(:configuration))
!RSpec::Mocks.configuration.verify_partial_doubles? ||
RSpec::Mocks.configuration.temporarily_suppress_partial_double_verification
end
def check_args_signature_mismatch(job_class, job_method, args)
signature = Support::MethodSignature.new(job_class.public_instance_method(job_method))
verifier = Support::StrictSignatureVerifier.new(signature, args)
unless verifier.valid?
"Incorrect arguments passed to #{job_class.name}: #{verifier.error_message}"
end
end
def queue_match?(job)
return true unless @queue
@queue == job[:queue]
end
def priority_match?(job)
return true unless @priority
@priority == job[:priority]
end
def at_match?(job)
return true unless @at
return job[:at].nil? if @at == :no_wait
return false unless job[:at]
scheduled_at = Time.at(job[:at])
values_match?(@at, scheduled_at) || check_for_inprecise_value(scheduled_at)
end
def check_for_inprecise_value(scheduled_at)
return unless Time === @at && values_match?(@at.change(usec: 0), scheduled_at)
RSpec.warn_with((<<-WARNING).gsub(/^\s+\|/, '').chomp)
|[WARNING] Your expected `at(...)` value does not match the job scheduled_at value
|unless microseconds are removed. This precision error often occurs when checking
|values against `Time.current` / `Time.now` which have usec precision, but Rails
|uses `n.seconds.from_now` internally which has a usec count of `0`.
|
|Use `change(usec: 0)` to correct these values. For example:
|
|`Time.current.change(usec: 0)`
|
|Note: RSpec cannot do this for you because jobs can be scheduled with usec
|precision and we do not know whether it is on purpose or not.
|
|
WARNING
false
end
def set_expected_number(relativity, count)
@expectation_type = relativity
@expected_number = case count
when :once then 1
when :twice then 2
when :thrice then 3
else Integer(count)
end
end
def serialize_and_deserialize_arguments(args)
serialized = ::ActiveJob::Arguments.serialize(args)
::ActiveJob::Arguments.deserialize(serialized)
rescue ::ActiveJob::SerializationError
args
end
def deserialize_arguments(job)
::ActiveJob::Arguments.deserialize(job[:args])
rescue ::ActiveJob::DeserializationError
job[:args]
end
def queue_adapter
::ActiveJob::Base.queue_adapter
end
end
# rubocop: enable Metrics/ClassLength
# @private
class HaveEnqueuedJob < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'enqueue'.freeze
MESSAGE_EXPECTATION_ACTION = 'enqueued'.freeze
def initialize(job)
super()
@job = job
end
def matches?(proc)
raise ArgumentError, "have_enqueued_job and enqueue_job only support block expectations" unless Proc === proc
original_enqueued_jobs = Set.new(queue_adapter.enqueued_jobs)
proc.call
enqueued_jobs = Set.new(queue_adapter.enqueued_jobs)
check(enqueued_jobs - original_enqueued_jobs)
end
def does_not_match?(proc)
set_expected_number(:at_least, 1)
!matches?(proc)
end
end
# @private
class HaveBeenEnqueued < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'enqueue'.freeze
MESSAGE_EXPECTATION_ACTION = 'enqueued'.freeze
def matches?(job)
@job = job
check(queue_adapter.enqueued_jobs)
end
def does_not_match?(proc)
set_expected_number(:at_least, 1)
!matches?(proc)
end
def supports_block_expectations?
false
end
end
# @private
class HavePerformedJob < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'perform'.freeze
MESSAGE_EXPECTATION_ACTION = 'performed'.freeze
def initialize(job)
super()
@job = job
end
def matches?(proc)
raise ArgumentError, "have_performed_job only supports block expectations" unless Proc === proc
original_performed_jobs_count = queue_adapter.performed_jobs.count
proc.call
in_block_jobs = queue_adapter.performed_jobs.drop(original_performed_jobs_count)
check(in_block_jobs)
end
end
# @private
class HaveBeenPerformed < Base
FAILURE_MESSAGE_EXPECTATION_ACTION = 'perform'.freeze
MESSAGE_EXPECTATION_ACTION = 'performed'.freeze
def matches?(job)
@job = job
check(queue_adapter.performed_jobs)
end
def supports_block_expectations?
false
end
end
end
# @api public
# Passes if a job has been enqueued inside block. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# expect {
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job
#
# # Using alias
# expect {
# HeavyLiftingJob.perform_later
# }.to enqueue_job
#
# expect {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job(HelloJob).exactly(:once)
#
# expect {
# 3.times { HelloJob.perform_later }
# }.to have_enqueued_job(HelloJob).at_least(2).times
#
# expect {
# HelloJob.perform_later
# }.to have_enqueued_job(HelloJob).at_most(:twice)
#
# expect {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }.to have_enqueued_job(HelloJob).and have_enqueued_job(HeavyLiftingJob)
#
# expect {
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# }.to have_enqueued_job.with(42).on_queue("low").at(Date.tomorrow.noon)
#
# expect {
# HelloJob.set(queue: "low").perform_later(42)
# }.to have_enqueued_job.with(42).on_queue("low").at(:no_wait)
#
# expect {
# HelloJob.perform_later('rspec_rails', 'rails', 42)
# }.to have_enqueued_job.with { |from, to, times|
# # Perform more complex argument matching using dynamic arguments
# expect(from).to include "_#{to}"
# }
def have_enqueued_job(job = nil)
check_active_job_adapter
ActiveJob::HaveEnqueuedJob.new(job)
end
alias_method :enqueue_job, :have_enqueued_job
# @api public
# Passes if a job has been enqueued. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear }
#
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_enqueued
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_enqueued.exactly(:once)
#
# 3.times { HelloJob.perform_later }
# expect(HelloJob).to have_been_enqueued.at_least(2).times
#
# HelloJob.perform_later
# expect(HelloJob).to enqueue_job(HelloJob).at_most(:twice)
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HelloJob).to have_been_enqueued
# expect(HeavyLiftingJob).to have_been_enqueued
#
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# expect(HelloJob).to have_been_enqueued.with(42).on_queue("low").at(Date.tomorrow.noon)
#
# HelloJob.set(queue: "low").perform_later(42)
# expect(HelloJob).to have_been_enqueued.with(42).on_queue("low").at(:no_wait)
def have_been_enqueued
check_active_job_adapter
ActiveJob::HaveBeenEnqueued.new
end
# @api public
# Passes if a job has been performed inside block. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# expect {
# perform_enqueued_jobs { HeavyLiftingJob.perform_later }
# }.to have_performed_job
#
# expect {
# perform_enqueued_jobs {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }
# }.to have_performed_job(HelloJob).exactly(:once)
#
# expect {
# perform_enqueued_jobs { 3.times { HelloJob.perform_later } }
# }.to have_performed_job(HelloJob).at_least(2).times
#
# expect {
# perform_enqueued_jobs { HelloJob.perform_later }
# }.to have_performed_job(HelloJob).at_most(:twice)
#
# expect {
# perform_enqueued_jobs {
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# }
# }.to have_performed_job(HelloJob).and have_performed_job(HeavyLiftingJob)
#
# expect {
# perform_enqueued_jobs {
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# }
# }.to have_performed_job.with(42).on_queue("low").at(Date.tomorrow.noon)
def have_performed_job(job = nil)
check_active_job_adapter
ActiveJob::HavePerformedJob.new(job)
end
alias_method :perform_job, :have_performed_job
# @api public
# Passes if a job has been performed. May chain at_least, at_most or exactly to specify a number of times.
#
# @example
# before do
# ActiveJob::Base.queue_adapter.performed_jobs.clear
# ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
# ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
# end
#
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_performed
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HeavyLiftingJob).to have_been_performed.exactly(:once)
#
# 3.times { HelloJob.perform_later }
# expect(HelloJob).to have_been_performed.at_least(2).times
#
# HelloJob.perform_later
# HeavyLiftingJob.perform_later
# expect(HelloJob).to have_been_performed
# expect(HeavyLiftingJob).to have_been_performed
#
# HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42)
# expect(HelloJob).to have_been_performed.with(42).on_queue("low").at(Date.tomorrow.noon)
def have_been_performed
check_active_job_adapter
ActiveJob::HaveBeenPerformed.new
end
private
# @private
def check_active_job_adapter
return if ::ActiveJob::QueueAdapters::TestAdapter === ::ActiveJob::Base.queue_adapter
raise StandardError, "To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/action_cable.rb | lib/rspec/rails/matchers/action_cable.rb | require "rspec/rails/matchers/action_cable/have_broadcasted_to"
module RSpec
module Rails
module Matchers
extend RSpec::Matchers::DSL
# Namespace for various implementations of ActionCable features
#
# @api private
module ActionCable
end
# @api public
# Passes if a message has been sent to a stream/object inside a block.
# May chain `at_least`, `at_most` or `exactly` to specify a number of times.
# To specify channel from which message has been broadcasted to object use `from_channel`.
#
#
# @example
# expect {
# ActionCable.server.broadcast "messages", text: 'Hi!'
# }.to have_broadcasted_to("messages")
#
# expect {
# SomeChannel.broadcast_to(user)
# }.to have_broadcasted_to(user).from_channel(SomeChannel)
#
# # Using alias
# expect {
# ActionCable.server.broadcast "messages", text: 'Hi!'
# }.to broadcast_to("messages")
#
# expect {
# ActionCable.server.broadcast "messages", text: 'Hi!'
# ActionCable.server.broadcast "all", text: 'Hi!'
# }.to have_broadcasted_to("messages").exactly(:once)
#
# expect {
# 3.times { ActionCable.server.broadcast "messages", text: 'Hi!' }
# }.to have_broadcasted_to("messages").at_least(2).times
#
# expect {
# ActionCable.server.broadcast "messages", text: 'Hi!'
# }.to have_broadcasted_to("messages").at_most(:twice)
#
# expect {
# ActionCable.server.broadcast "messages", text: 'Hi!'
# }.to have_broadcasted_to("messages").with(text: 'Hi!')
def have_broadcasted_to(target = nil)
check_action_cable_adapter
ActionCable::HaveBroadcastedTo.new(target, channel: described_class)
end
alias_matcher :broadcast_to, :have_broadcasted_to do |desc|
desc.gsub("have broadcasted", "broadcast")
end
private
# @private
def check_action_cable_adapter
return if ::ActionCable::SubscriptionAdapter::Test === ::ActionCable.server.pubsub
raise StandardError, "To use ActionCable matchers set `adapter: test` in your cable.yml"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/action_mailbox.rb | lib/rspec/rails/matchers/action_mailbox.rb | module RSpec
module Rails
module Matchers
# Namespace for various implementations of ActionMailbox features
#
# @api private
module ActionMailbox
# @private
class Base < RSpec::Rails::Matchers::BaseMatcher
private
def create_inbound_email(message)
RSpec::Rails::MailboxExampleGroup.create_inbound_email(message)
end
end
# @private
class ReceiveInboundEmail < Base
def initialize(message)
super()
@inbound_email = create_inbound_email(message)
end
if defined?(::ApplicationMailbox) && ::ApplicationMailbox.router.respond_to?(:mailbox_for)
def matches?(mailbox)
@mailbox = mailbox
@receiver = ApplicationMailbox.router.mailbox_for(inbound_email)
@receiver == @mailbox
end
else
def matches?(mailbox)
@mailbox = mailbox
@receiver = ApplicationMailbox.router.send(:match_to_mailbox, inbound_email)
@receiver == @mailbox
end
end
def failure_message
"expected #{describe_inbound_email} to route to #{mailbox}".tap do |msg|
if receiver
msg << ", but routed to #{receiver} instead"
end
end
end
def failure_message_when_negated
"expected #{describe_inbound_email} not to route to #{mailbox}"
end
private
attr_reader :inbound_email, :mailbox, :receiver
def describe_inbound_email
"mail to #{inbound_email.mail.to.to_sentence}"
end
end
end
# @api public
# Passes if the given inbound email would be routed to the subject inbox.
#
# @param message [Hash, Mail::Message] a mail message or hash of
# attributes used to build one
def receive_inbound_email(message)
ActionMailbox::ReceiveInboundEmail.new(message)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/be_valid.rb | lib/rspec/rails/matchers/be_valid.rb | module RSpec
module Rails
module Matchers
# @private
class BeValid < RSpec::Matchers::BuiltIn::Be
def initialize(*args)
@args = args
end
def matches?(actual)
@actual = actual
actual.valid?(*@args)
end
def failure_message
message = "expected #{actual.inspect} to be valid"
if actual.respond_to?(:errors) && actual.method(:errors).arity < 1
errors = if actual.errors.respond_to?(:full_messages)
actual.errors.full_messages
else
actual.errors
end
message << ", but got errors: #{errors.map(&:to_s).join(', ')}"
end
message
end
def failure_message_when_negated
"expected #{actual.inspect} not to be valid"
end
end
# @api public
# Passes if the given model instance's `valid?` method is true, meaning
# all of the `ActiveModel::Validations` passed and no errors exist. If a
# message is not given, a default message is shown listing each error.
#
# @example
# thing = Thing.new
# expect(thing).to be_valid
def be_valid(*args)
BeValid.new(*args)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/have_rendered.rb | lib/rspec/rails/matchers/have_rendered.rb | module RSpec
module Rails
module Matchers
# Matcher for template rendering.
module RenderTemplate
# @private
class RenderTemplateMatcher < RSpec::Rails::Matchers::BaseMatcher
def initialize(scope, expected, message = nil)
@expected = Symbol === expected ? expected.to_s : expected
@message = message
@scope = scope
@redirect_is = nil
end
# @api private
def matches?(*)
match_check = match_unless_raises ActiveSupport::TestCase::Assertion do
@scope.assert_template expected, @message
end
check_redirect unless match_check
match_check
end
# Uses normalize_argument_to_redirection to find and format
# the redirect location. normalize_argument_to_redirection is private
# in ActionDispatch::Assertions::ResponseAssertions so we call it
# here using #send. This will keep the error message format consistent
# @api private
def check_redirect
response = @scope.response
return unless response.respond_to?(:redirect?) && response.redirect?
@redirect_is = @scope.send(:normalize_argument_to_redirection, response.location)
end
# @api private
def failure_message
if @redirect_is
rescued_exception.message[/(.*?)( but|$)/, 1] +
" but was a redirect to <#{@redirect_is}>"
else
rescued_exception.message
end
end
# @api private
def failure_message_when_negated
"expected not to render #{expected.inspect}, but did"
end
end
# Delegates to `assert_template`.
#
# @example
# expect(response).to have_rendered("new")
def have_rendered(options, message = nil)
RenderTemplateMatcher.new(self, options, message)
end
alias_method :render_template, :have_rendered
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/have_http_status.rb | lib/rspec/rails/matchers/have_http_status.rb | # The following code inspired and modified from Rails' `assert_response`:
#
# https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/assertions/response.rb#L22-L38
#
# Thank you to all the Rails devs who did the heavy lifting on this!
module RSpec
module Rails
module Matchers
# Namespace for various implementations of `have_http_status`.
#
# @api private
module HaveHttpStatus
# Instantiates an instance of the proper matcher based on the provided
# `target`.
#
# @param target [Object] expected http status or code
# @return response matcher instance
def self.matcher_for_status(target)
if GenericStatus.valid_statuses.include?(target)
GenericStatus.new(target)
elsif Symbol === target
SymbolicStatus.new(target)
else
NumericCode.new(target)
end
end
# @api private
# Conversion function to coerce the provided object into an
# `ActionDispatch::TestResponse`.
#
# @param obj [Object] object to convert to a response
# @return [ActionDispatch::TestResponse]
def as_test_response(obj)
if ::ActionDispatch::Response === obj || ::Rack::MockResponse === obj
::ActionDispatch::TestResponse.from_response(obj)
elsif ::ActionDispatch::TestResponse === obj
obj
elsif obj.respond_to?(:status_code) && obj.respond_to?(:response_headers)
# Acts As Capybara Session
# Hack to support `Capybara::Session` without having to load
# Capybara or catch `NameError`s for the undefined constants
obj = ActionDispatch::Response.new.tap do |resp|
resp.status = obj.status_code
resp.headers.clear
resp.headers.merge!(obj.response_headers)
resp.body = obj.body
resp.request = ActionDispatch::Request.new({})
end
::ActionDispatch::TestResponse.from_response(obj)
else
raise TypeError, "Invalid response type: #{obj}"
end
end
module_function :as_test_response
# @return [String, nil] a formatted failure message if
# `@invalid_response` is present, `nil` otherwise
def invalid_response_type_message
return unless @invalid_response
"expected a response object, but an instance of " \
"#{@invalid_response.class} was received"
end
# @api private
# Provides an implementation for `have_http_status` matching against
# numeric http status codes.
#
# Not intended to be instantiated directly.
#
# @example
# expect(response).to have_http_status(404)
#
# @see RSpec::Rails::Matchers#have_http_status
class NumericCode < RSpec::Rails::Matchers::BaseMatcher
include HaveHttpStatus
def initialize(code)
@expected = code.to_i
@actual = nil
@invalid_response = nil
end
# @param [Object] response object providing an http code to match
# @return [Boolean] `true` if the numeric code matched the `response` code
def matches?(response)
test_response = as_test_response(response)
@actual = test_response.response_code.to_i
expected == @actual
rescue TypeError => _ignored
@invalid_response = response
false
end
# @return [String]
def description
"respond with numeric status code #{expected}"
end
# @return [String] explaining why the match failed
def failure_message
invalid_response_type_message ||
"expected the response to have status code #{expected.inspect}" \
" but it was #{actual.inspect}"
end
# @return [String] explaining why the match failed
def failure_message_when_negated
invalid_response_type_message ||
"expected the response not to have status code " \
"#{expected.inspect} but it did"
end
end
# @api private
# Provides an implementation for `have_http_status` matching against
# Rack symbol http status codes.
#
# Not intended to be instantiated directly.
#
# @example
# expect(response).to have_http_status(:created)
#
# @see RSpec::Rails::Matchers#have_http_status
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
class SymbolicStatus < RSpec::Rails::Matchers::BaseMatcher
include HaveHttpStatus
def initialize(status)
@expected_status = status
@actual = nil
@invalid_response = nil
set_expected_code!
end
# @param [Object] response object providing an http code to match
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
# the `response` code
def matches?(response)
test_response = as_test_response(response)
@actual = test_response.response_code
expected == @actual
rescue TypeError => _ignored
@invalid_response = response
false
end
# @return [String]
def description
"respond with status code #{pp_expected}"
end
# @return [String] explaining why the match failed
def failure_message
invalid_response_type_message ||
"expected the response to have status code #{pp_expected} but it" \
" was #{pp_actual}"
end
# @return [String] explaining why the match failed
def failure_message_when_negated
invalid_response_type_message ||
"expected the response not to have status code #{pp_expected} " \
"but it did"
end
# The initialized expected status symbol
attr_reader :expected_status
private :expected_status
private
# @return [Symbol] representing the actual http numeric code
def actual_status
return unless actual
@actual_status ||= compute_status_from(actual)
end
# Reverse lookup of the Rack status code symbol based on the numeric
# http code
#
# @param code [Fixnum] http status code to look up
# @return [Symbol] representing the http numeric code
def compute_status_from(code)
status, _ = Rack::Utils::SYMBOL_TO_STATUS_CODE.find do |_, c|
c == code
end
status
end
# @return [String] pretty format the actual response status
def pp_actual
pp_status(actual_status, actual)
end
# @return [String] pretty format the expected status and associated code
def pp_expected
pp_status(expected_status, expected)
end
# @return [String] pretty format the actual response status
def pp_status(status, code)
if status
"#{status.inspect} (#{code})"
else
code.to_s
end
end
# Sets `expected` to the numeric http code based on the Rack
# `expected_status` status
#
# @see Rack::Utils::SYMBOL_TO_STATUS_CODE
# @raise [ArgumentError] if an associated code could not be found
def set_expected_code!
@expected ||= Rack::Utils.status_code(expected_status)
end
end
# @api private
# Provides an implementation for `have_http_status` matching against
# `ActionDispatch::TestResponse` http status category queries.
#
# Not intended to be instantiated directly.
#
# @example
# expect(response).to have_http_status(:success)
# expect(response).to have_http_status(:error)
# expect(response).to have_http_status(:missing)
# expect(response).to have_http_status(:redirect)
#
# @see RSpec::Rails::Matchers#have_http_status
# @see https://github.com/rails/rails/blob/7-2-stable/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
class GenericStatus < RSpec::Rails::Matchers::BaseMatcher
include HaveHttpStatus
# @return [Array<Symbol>] of status codes which represent a HTTP status
# code "group"
# @see https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
def self.valid_statuses
[
:error, :success, :missing,
:server_error, :successful, :not_found,
:redirect
]
end
def initialize(type)
unless self.class.valid_statuses.include?(type)
raise ArgumentError, "Invalid generic HTTP status: #{type.inspect}"
end
@expected = type
@actual = nil
@invalid_response = nil
end
# @return [Boolean] `true` if Rack's associated numeric HTTP code matched
# the `response` code or the named response status
def matches?(response)
test_response = as_test_response(response)
@actual = test_response.response_code
check_expected_status(test_response, expected)
rescue TypeError => _ignored
@invalid_response = response
false
end
# @return [String]
def description
"respond with #{type_message}"
end
# @return [String] explaining why the match failed
def failure_message
invalid_response_type_message ||
"expected the response to have #{type_message} but it was #{actual}"
end
# @return [String] explaining why the match failed
def failure_message_when_negated
invalid_response_type_message ||
"expected the response not to have #{type_message} but it was #{actual}"
end
protected
RESPONSE_METHODS = {
success: 'successful',
error: 'server_error',
missing: 'not_found'
}.freeze
def check_expected_status(test_response, expected)
test_response.send(
"#{RESPONSE_METHODS.fetch(expected, expected)}?")
end
private
# @return [String] formatting the expected status and associated code(s)
def type_message
@type_message ||= (expected == :error ? "an error" : "a #{expected}") +
" status code (#{type_codes})"
end
# @return [String] formatting the associated code(s) for the various
# status code "groups"
# @see https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
# @see https://github.com/rack/rack/blob/master/lib/rack/response.rb `Rack::Response`
def type_codes
# At the time of this commit the most recent version of
# `ActionDispatch::TestResponse` defines the following aliases:
#
# alias_method :success?, :successful?
# alias_method :missing?, :not_found?
# alias_method :redirect?, :redirection?
# alias_method :error?, :server_error?
#
# It's parent `ActionDispatch::Response` includes
# `Rack::Response::Helpers` which defines the aliased methods as:
#
# def successful?; status >= 200 && status < 300; end
# def redirection?; status >= 300 && status < 400; end
# def server_error?; status >= 500 && status < 600; end
# def not_found?; status == 404; end
#
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L17-L27
# @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/http/response.rb#L74
# @see https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119-L122
@type_codes ||= case expected
when :error, :server_error
"5xx"
when :success, :successful
"2xx"
when :missing, :not_found
"404"
when :redirect
"3xx"
end
end
end
end
# @api public
# Passes if `response` has a matching HTTP status code.
#
# The following symbolic status codes are allowed:
#
# - `Rack::Utils::SYMBOL_TO_STATUS_CODE`
# - One of the defined `ActionDispatch::TestResponse` aliases:
# - `:error`
# - `:missing`
# - `:redirect`
# - `:success`
#
# @example Accepts numeric and symbol statuses
# expect(response).to have_http_status(404)
# expect(response).to have_http_status(:created)
# expect(response).to have_http_status(:success)
# expect(response).to have_http_status(:error)
# expect(response).to have_http_status(:missing)
# expect(response).to have_http_status(:redirect)
#
# @example Works with standard `response` objects and Capybara's `page`
# expect(response).to have_http_status(404)
# expect(page).to have_http_status(:created)
#
# @see https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse`
# @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE`
def have_http_status(target)
raise ArgumentError, "Invalid HTTP status: nil" unless target
HaveHttpStatus.matcher_for_status(target)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/redirect_to.rb | lib/rspec/rails/matchers/redirect_to.rb | module RSpec
module Rails
module Matchers
# Matcher for redirects.
module RedirectTo
# @private
class RedirectTo < RSpec::Rails::Matchers::BaseMatcher
def initialize(scope, expected)
@expected = expected
@scope = scope
end
def matches?(_)
match_unless_raises ActiveSupport::TestCase::Assertion do
@scope.assert_redirected_to(@expected)
end
end
def failure_message
rescued_exception.message
end
def failure_message_when_negated
"expected not to redirect to #{@expected.inspect}, but did"
end
end
# Delegates to `assert_redirected_to`.
#
# @example
# expect(response).to redirect_to(:action => "new")
def redirect_to(target)
RedirectTo.new(self, target)
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/be_a_new.rb | lib/rspec/rails/matchers/be_a_new.rb | module RSpec
module Rails
module Matchers
# @api private
#
# Matcher class for `be_a_new`. Should not be instantiated directly.
#
# @see RSpec::Rails::Matchers#be_a_new
class BeANew < RSpec::Rails::Matchers::BaseMatcher
# @private
def initialize(expected)
@expected = expected
end
# @private
def matches?(actual)
@actual = actual
actual.is_a?(expected) && actual.new_record? && attributes_match?(actual)
end
# @api public
# @see RSpec::Rails::Matchers#be_a_new
def with(expected_attributes)
attributes.merge!(expected_attributes)
self
end
# @private
def failure_message
[].tap do |message|
unless actual.is_a?(expected) && actual.new_record?
message << "expected #{actual.inspect} to be a new #{expected.inspect}"
end
unless attributes_match?(actual)
describe_unmatched_attributes = surface_descriptions_in(unmatched_attributes)
if unmatched_attributes.size > 1
message << "attributes #{describe_unmatched_attributes.inspect} were not set on #{actual.inspect}"
else
message << "attribute #{describe_unmatched_attributes.inspect} was not set on #{actual.inspect}"
end
end
end.join(' and ')
end
private
def attributes
@attributes ||= {}
end
def attributes_match?(actual)
attributes.stringify_keys.all? do |key, value|
values_match?(value, actual.attributes[key])
end
end
def unmatched_attributes
attributes.stringify_keys.reject do |key, value|
values_match?(value, actual.attributes[key])
end
end
end
# @api public
# Passes if actual is an instance of `model_class` and returns `true` for
# `new_record?`. Typically used to specify instance variables assigned to
# views by controller actions
#
# Use the `with` method to specify the specific attributes to match on the
# new record.
#
# @example
# get :new
# assigns(:thing).should be_a_new(Thing)
#
# post :create, :thing => { :name => "Illegal Value" }
# assigns(:thing).should be_a_new(Thing).with(:name => nil)
def be_a_new(model_class)
BeANew.new(model_class)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/routing_matchers.rb | lib/rspec/rails/matchers/routing_matchers.rb | module RSpec
module Rails
module Matchers
# Matchers to help with specs for routing code.
module RoutingMatchers
extend RSpec::Matchers::DSL
# @private
class RouteToMatcher < RSpec::Rails::Matchers::BaseMatcher
def initialize(scope, *expected)
@scope = scope
@expected = expected[1] || {}
if Hash === expected[0]
@expected.merge!(expected[0])
else
controller, action = expected[0].split('#')
@expected.merge!(controller: controller, action: action)
end
end
def matches?(verb_to_path_map)
@actual = verb_to_path_map
# assert_recognizes does not consider ActionController::RoutingError an
# assertion failure, so we have to capture that and Assertion here.
match_unless_raises ActiveSupport::TestCase::Assertion, ActionController::RoutingError do
path, query = *verb_to_path_map.values.first.split('?')
@scope.assert_recognizes(
@expected,
{ method: verb_to_path_map.keys.first, path: path },
Rack::Utils.parse_nested_query(query)
)
end
end
def failure_message
rescued_exception.message
end
def failure_message_when_negated
"expected #{@actual.inspect} not to route to #{@expected.inspect}"
end
def description
"route #{@actual.inspect} to #{@expected.inspect}"
end
end
# Delegates to `assert_recognizes`. Supports short-hand controller/action
# declarations (e.g. `"controller#action"`).
#
# @example
#
# expect(get: "/things/special").to route_to(
# controller: "things",
# action: "special"
# )
#
# expect(get: "/things/special").to route_to("things#special")
#
# @see https://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes
def route_to(*expected)
RouteToMatcher.new(self, *expected)
end
# @private
class BeRoutableMatcher < RSpec::Rails::Matchers::BaseMatcher
def initialize(scope)
@scope = scope
end
def matches?(path)
@actual = path
match_unless_raises ActionController::RoutingError do
@routing_options = @scope.routes.recognize_path(
path.values.first, method: path.keys.first
)
end
end
def failure_message
"expected #{@actual.inspect} to be routable"
end
def failure_message_when_negated
"expected #{@actual.inspect} not to be routable, but it routes to #{@routing_options.inspect}"
end
def description
"be routable"
end
end
# Passes if the route expression is recognized by the Rails router based on
# the declarations in `config/routes.rb`. Delegates to
# `RouteSet#recognize_path`.
#
# @example You can use route helpers provided by rspec-rails.
# expect(get: "/a/path").to be_routable
# expect(post: "/another/path").to be_routable
# expect(put: "/yet/another/path").to be_routable
def be_routable
BeRoutableMatcher.new(self)
end
# Helpers for matching different route types.
module RouteHelpers
# @!method get
# @!method post
# @!method put
# @!method patch
# @!method delete
# @!method options
# @!method head
#
# Shorthand method for matching this type of route.
%w[get post put patch delete options head].each do |method|
define_method method do |path|
{ method.to_sym => path }
end
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/be_new_record.rb | lib/rspec/rails/matchers/be_new_record.rb | module RSpec
module Rails
module Matchers
# @private
class BeANewRecord < RSpec::Rails::Matchers::BaseMatcher
def matches?(actual)
actual.new_record?
end
def failure_message
"expected #{actual.inspect} to be a new record, but was persisted"
end
def failure_message_when_negated
"expected #{actual.inspect} to be persisted, but was a new record"
end
end
# @api public
# Passes if actual returns `true` for `new_record?`.
#
# @example
# get :new
# expect(assigns(:thing)).to be_new_record
def be_new_record
BeANewRecord.new
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/relation_match_array.rb | lib/rspec/rails/matchers/relation_match_array.rb | if defined?(ActiveRecord::Relation) && defined?(RSpec::Matchers::BuiltIn::OperatorMatcher) # RSpec 4 removed OperatorMatcher
RSpec::Matchers::BuiltIn::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::BuiltIn::ContainExactly)
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/send_email.rb | lib/rspec/rails/matchers/send_email.rb | # frozen_string_literal: true
module RSpec
module Rails
module Matchers
# @api private
#
# Matcher class for `send_email`. Should not be instantiated directly.
#
# @see RSpec::Rails::Matchers#send_email
class SendEmail < RSpec::Rails::Matchers::BaseMatcher
# @api private
# Define the email attributes that should be included in the inspection output.
INSPECT_EMAIL_ATTRIBUTES = %i[subject from to cc bcc].freeze
def initialize(criteria)
@criteria = criteria
end
# @api private
def supports_value_expectations?
false
end
# @api private
def supports_block_expectations?
true
end
def matches?(block)
define_matched_emails(block)
@matched_emails.one?
end
# @api private
# @return [String]
def failure_message
result =
if multiple_match?
"More than 1 matching emails were sent."
else
"No matching emails were sent."
end
"#{result}#{sent_emails_message}"
end
# @api private
# @return [String]
def failure_message_when_negated
"Expected not to send an email but it was sent."
end
private
def diffable?
true
end
def deliveries
ActionMailer::Base.deliveries
end
def define_matched_emails(block)
before = deliveries.dup
block.call
after = deliveries
@diff = after - before
@matched_emails = @diff.select(&method(:matched_email?))
end
def matched_email?(email)
@criteria.all? do |attr, value|
expected =
case attr
when :to, :from, :cc, :bcc then Array(value)
else
value
end
values_match?(expected, email.public_send(attr))
end
end
def multiple_match?
@matched_emails.many?
end
def sent_emails_message
if @diff.empty?
"\n\nThere were no any emails sent inside the expectation block."
else
sent_emails =
@diff.map do |email|
inspected = INSPECT_EMAIL_ATTRIBUTES.map { |attr| "#{attr}: #{email.public_send(attr)}" }.join(", ")
"- #{inspected}"
end.join("\n")
"\n\nThe following emails were sent:\n#{sent_emails}"
end
end
end
# @api public
# Check email sending with specific parameters.
#
# @example Positive expectation
# expect { action }.to send_email
#
# @example Negative expectations
# expect { action }.not_to send_email
#
# @example More precise expectation with attributes to match
# expect { action }.to send_email(to: 'test@example.com', subject: 'Confirm email')
def send_email(criteria = {})
SendEmail.new(criteria)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/action_cable/have_streams.rb | lib/rspec/rails/matchers/action_cable/have_streams.rb | module RSpec
module Rails
module Matchers
module ActionCable
# @api private
# Provides the implementation for `have_stream`, `have_stream_for`, and `have_stream_from`.
# Not intended to be instantiated directly.
class HaveStream < RSpec::Matchers::BuiltIn::BaseMatcher
# @api private
# @return [String]
def failure_message
"expected to have #{base_message}"
end
# @api private
# @return [String]
def failure_message_when_negated
"expected not to have #{base_message}"
end
# @api private
# @return [Boolean]
def matches?(subscription)
raise(ArgumentError, "have_streams is used for negated expectations only") if no_expected?
match(subscription)
end
# @api private
# @return [Boolean]
def does_not_match?(subscription)
!match(subscription)
end
private
def match(subscription)
case subscription
when ::ActionCable::Channel::Base
@actual = subscription.streams
no_expected? ? actual.any? : actual.any? { |i| expected === i }
else
raise ArgumentError, "have_stream, have_stream_from and have_stream_from support expectations on subscription only"
end
end
def base_message
no_expected? ? "any stream started" : "stream #{expected_formatted} started, but have #{actual_formatted}"
end
def no_expected?
!defined?(@expected)
end
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/rspec/rails/matchers/action_cable/have_broadcasted_to.rb | lib/rspec/rails/matchers/action_cable/have_broadcasted_to.rb | module RSpec
module Rails
module Matchers
module ActionCable
# rubocop: disable Metrics/ClassLength
# @private
class HaveBroadcastedTo < RSpec::Matchers::BuiltIn::BaseMatcher
def initialize(target, channel:)
@target = target
@channel = channel
@block = proc { }
@data = nil
set_expected_number(:exactly, 1)
end
def with(data = nil, &block)
@data = data
@data = @data.with_indifferent_access if @data.is_a?(Hash)
@block = block if block
self
end
def exactly(count)
set_expected_number(:exactly, count)
self
end
def at_least(count)
set_expected_number(:at_least, count)
self
end
def at_most(count)
set_expected_number(:at_most, count)
self
end
def times
self
end
def once
exactly(:once)
end
def twice
exactly(:twice)
end
def thrice
exactly(:thrice)
end
def description
"have broadcasted #{base_description}"
end
def failure_message
"expected to broadcast #{base_message}".tap do |msg|
if @unmatching_msgs.any?
msg << "\nBroadcasted messages to #{stream}:"
@unmatching_msgs.each do |data|
msg << "\n #{data}"
end
end
end
end
def failure_message_when_negated
"expected not to broadcast #{base_message}"
end
def message_expectation_modifier
case @expectation_type
when :exactly then "exactly"
when :at_most then "at most"
when :at_least then "at least"
end
end
def supports_block_expectations?
true
end
def matches?(proc)
raise ArgumentError, "have_broadcasted_to and broadcast_to only support block expectations" unless Proc === proc
original_sent_messages_count = pubsub_adapter.broadcasts(stream).size
proc.call
in_block_messages = pubsub_adapter.broadcasts(stream).drop(original_sent_messages_count)
check(in_block_messages)
end
def from_channel(channel)
@channel = channel
self
end
private
def stream
@stream ||= case @target
when String
@target
when Symbol
@target.to_s
else
check_channel_presence
@channel.broadcasting_for(@target)
end
end
def check(messages)
@matching_msgs, @unmatching_msgs = messages.partition do |msg|
decoded = ActiveSupport::JSON.decode(msg)
decoded = decoded.with_indifferent_access if decoded.is_a?(Hash)
if @data.nil? || values_match?(@data, decoded)
@block.call(decoded)
true
else
false
end
end
@matching_msgs_count = @matching_msgs.size
case @expectation_type
when :exactly then @expected_number == @matching_msgs_count
when :at_most then @expected_number >= @matching_msgs_count
when :at_least then @expected_number <= @matching_msgs_count
end
end
def set_expected_number(relativity, count)
@expectation_type = relativity
@expected_number =
case count
when :once then 1
when :twice then 2
when :thrice then 3
else Integer(count)
end
end
def base_description
"#{message_expectation_modifier} #{@expected_number} messages to #{stream}".tap do |msg|
msg << " with #{data_description(@data)}" unless @data.nil?
end
end
def base_message
"#{base_description}, but broadcast #{@matching_msgs_count}"
end
def data_description(data)
if data.is_a?(RSpec::Matchers::Composable)
data.description
else
data.inspect
end
end
def pubsub_adapter
::ActionCable.server.pubsub
end
def check_channel_presence
return if @channel.present? && @channel.respond_to?(:channel_name)
error_msg = "Broadcasting channel can't be inferred. Please, specify it with `from_channel`"
raise ArgumentError, error_msg
end
end
# rubocop: enable Metrics/ClassLength
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec.rb | lib/generators/rspec.rb | require 'rails/generators/named_base'
require 'rspec/core'
require 'rspec/rails/feature_check'
# @private
# Weirdly named generators namespace (should be `RSpec`) for compatibility with
# rails loading.
module Rspec
# @private
module Generators
# @private
class Base < ::Rails::Generators::NamedBase
include RSpec::Rails::FeatureCheck
def self.source_root(path = nil)
if path
@_rspec_source_root = path
else
@_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates'))
end
end
# @private
# Load configuration from RSpec to ensure `--default-path` is set
def self.configuration
@configuration ||=
begin
configuration = RSpec.configuration
options = RSpec::Core::ConfigurationOptions.new({})
options.configure(configuration)
configuration
end
end
def target_path(*paths)
File.join(self.class.configuration.default_path, *paths)
end
end
end
end
# @private
module Rails
module Generators
# @private
class GeneratedAttribute
def input_type
@input_type ||= if type == :text
"textarea"
else
"input"
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/controller/controller_generator.rb | lib/generators/rspec/controller/controller_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class ControllerGenerator < Base
argument :actions, type: :array, default: [], banner: "action action"
class_option :template_engine, desc: "Template engine to generate view files"
class_option :request_specs, type: :boolean, default: true, desc: "Generate request specs"
class_option :controller_specs, type: :boolean, default: false, desc: "Generate controller specs"
class_option :view_specs, type: :boolean, default: true, desc: "Generate view specs"
class_option :routing_specs, type: :boolean, default: false, desc: "Generate routing specs"
def generate_request_spec
return unless options[:request_specs]
template 'request_spec.rb',
target_path('requests', class_path, "#{file_name}_spec.rb")
end
def generate_controller_spec
return unless options[:controller_specs]
template 'controller_spec.rb',
target_path('controllers', class_path, "#{file_name}_controller_spec.rb")
end
def generate_view_specs
return if actions.empty? && behavior == :invoke
return unless options[:view_specs] && options[:template_engine]
empty_directory File.join("spec", "views", file_path)
actions.each do |action|
@action = action
template 'view_spec.rb',
target_path('views', file_path, "#{@action}.html.#{options[:template_engine]}_spec.rb")
end
end
def generate_routing_spec
return if actions.empty?
return unless options[:routing_specs]
template 'routing_spec.rb',
target_path('routing', class_path, "#{file_name}_routing_spec.rb")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/controller/templates/routing_spec.rb | lib/generators/rspec/controller/templates/routing_spec.rb | require 'rails_helper'
<% module_namespacing do -%>
RSpec.describe '<%= class_name %>Controller', <%= type_metatag(:routing) %> do
describe 'routing' do
<% for action in actions -%>
it 'routes to #<%= action %>' do
expect(get: "/<%= class_name.underscore %>/<%= action %>").to route_to("<%= class_name.underscore %>#<%= action %>")
end
<% end -%>
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/controller/templates/view_spec.rb | lib/generators/rspec/controller/templates/view_spec.rb | require 'rails_helper'
RSpec.describe "<%= file_name %>/<%= @action %>.html.<%= options[:template_engine] %>", <%= type_metatag(:view) %> do
pending "add some examples to (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/controller/templates/request_spec.rb | lib/generators/rspec/controller/templates/request_spec.rb | require 'rails_helper'
RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do
<% namespaced_path = regular_class_path.join('/') -%>
<% if actions.empty? -%>
describe "GET /index" do
pending "add some examples (or delete) #{__FILE__}"
end
<% end -%>
<% for action in actions -%>
describe "GET /<%= action %>" do
it "returns http success" do
get "<%= "/#{namespaced_path}" if namespaced_path != '' %>/<%= file_name %>/<%= action %>"
expect(response).to have_http_status(:success)
end
end
<% end -%>
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/controller/templates/controller_spec.rb | lib/generators/rspec/controller/templates/controller_spec.rb | require 'rails_helper'
<% module_namespacing do -%>
RSpec.describe <%= class_name %>Controller, <%= type_metatag(:controller) %> do
<% for action in actions -%>
describe "GET #<%= action %>" do
it "returns http success" do
get :<%= action %>
expect(response).to have_http_status(:success)
end
end
<% end -%>
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/system/system_generator.rb | lib/generators/rspec/system/system_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class SystemGenerator < Base
class_option :system_specs, type: :boolean, default: true, desc: "Generate system specs"
def generate_system_spec
return unless options[:system_specs]
template template_name, target_path('system', class_path, filename)
end
def template_name
'system_spec.rb'
end
def filename
"#{table_name}_spec.rb"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/system/templates/system_spec.rb | lib/generators/rspec/system/templates/system_spec.rb | require 'rails_helper'
RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:system) %> do
before do
driven_by(:rack_test)
end
pending "add some scenarios (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/scaffold_generator.rb | lib/generators/rspec/scaffold/scaffold_generator.rb | require 'generators/rspec'
require 'rails/generators/resource_helpers'
module Rspec
module Generators
# @private
class ScaffoldGenerator < Base
include ::Rails::Generators::ResourceHelpers
source_paths << File.expand_path('../helper/templates', __dir__)
argument :attributes, type: :array, default: [], banner: "field:type field:type"
class_option :orm, desc: "ORM used to generate the controller"
class_option :template_engine, desc: "Template engine to generate view files"
class_option :singleton, type: :boolean, desc: "Supply to create a singleton controller"
class_option :api, type: :boolean, desc: "Skip specs unnecessary for API-only apps"
class_option :controller_specs, type: :boolean, default: false, desc: "Generate controller specs"
class_option :request_specs, type: :boolean, default: true, desc: "Generate request specs"
class_option :view_specs, type: :boolean, default: true, desc: "Generate view specs"
class_option :helper_specs, type: :boolean, default: true, desc: "Generate helper specs"
class_option :routing_specs, type: :boolean, default: true, desc: "Generate routing specs"
def initialize(*args, &blk)
@generator_args = args.first
super(*args, &blk)
end
def generate_controller_spec
return unless options[:controller_specs]
if options[:api]
template 'api_controller_spec.rb', template_file(folder: 'controllers', suffix: '_controller')
else
template 'controller_spec.rb', template_file(folder: 'controllers', suffix: '_controller')
end
end
def generate_request_spec
return unless options[:request_specs]
if options[:api]
template 'api_request_spec.rb', template_file(folder: 'requests')
else
template 'request_spec.rb', template_file(folder: 'requests')
end
end
def generate_view_specs
return if options[:api]
return unless options[:view_specs] && options[:template_engine]
copy_view :edit
copy_view :index unless options[:singleton]
copy_view :new
copy_view :show
end
def generate_routing_spec
return unless options[:routing_specs]
template_file = target_path(
'routing',
controller_class_path,
"#{controller_file_name}_routing_spec.rb"
)
template 'routing_spec.rb', template_file
end
protected
attr_reader :generator_args
def copy_view(view)
template "#{view}_spec.rb",
target_path("views", controller_file_path, "#{view}.html.#{options[:template_engine]}_spec.rb")
end
# support for namespaced-resources
def ns_file_name
return file_name if ns_parts.empty?
"#{ns_prefix.map(&:underscore).join('/')}_#{ns_suffix.singularize.underscore}"
end
# support for namespaced-resources
def ns_table_name
return table_name if ns_parts.empty?
"#{ns_prefix.map(&:underscore).join('/')}/#{ns_suffix.tableize}"
end
def ns_parts
@ns_parts ||= begin
parts = generator_args[0].split(/\/|::/)
parts.size > 1 ? parts : []
end
end
def ns_prefix
@ns_prefix ||= ns_parts[0..-2]
end
def ns_suffix
@ns_suffix ||= ns_parts[-1]
end
def value_for(attribute)
raw_value_for(attribute).inspect
end
def raw_value_for(attribute)
case attribute.type
when :string
attribute.name.titleize
when :integer, :float
@attribute_id_map ||= {}
@attribute_id_map[attribute] ||= @attribute_id_map.keys.size.next + attribute.default
else
attribute.default
end
end
def template_file(folder:, suffix: '')
target_path(folder, controller_class_path, "#{controller_file_name}#{suffix}_spec.rb")
end
def banner
self.class.banner
end
def show_helper(resource_name = file_name)
"#{singular_route_name}_url(#{resource_name})"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/show_spec.rb | lib/generators/rspec/scaffold/templates/show_spec.rb | require 'rails_helper'
<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
RSpec.describe "<%= ns_table_name %>/show", <%= type_metatag(:view) %> do
before(:each) do
assign(:<%= singular_table_name %>, <%= class_name %>.create!(<%= '))' if output_attributes.empty? %>
<% output_attributes.each_with_index do |attribute, attribute_index| -%>
<%= attribute.name %>: <%= value_for(attribute) %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
<% end -%>
<% if !output_attributes.empty? -%>
))
<% end -%>
end
it "renders attributes in <p>" do
render
<% for attribute in output_attributes -%>
expect(rendered).to match(/<%= raw_value_for(attribute) %>/)
<% end -%>
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/routing_spec.rb | lib/generators/rspec/scaffold/templates/routing_spec.rb | require "rails_helper"
<% module_namespacing do -%>
RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(:routing) %> do
describe "routing" do
<% unless options[:singleton] -%>
it "routes to #index" do
expect(get: "/<%= ns_table_name %>").to route_to("<%= ns_table_name %>#index")
end
<% end -%>
<% unless options[:api] -%>
it "routes to #new" do
expect(get: "/<%= ns_table_name %>/new").to route_to("<%= ns_table_name %>#new")
end
<% end -%>
it "routes to #show" do
expect(get: "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#show", id: "1")
end
<% unless options[:api] -%>
it "routes to #edit" do
expect(get: "/<%= ns_table_name %>/1/edit").to route_to("<%= ns_table_name %>#edit", id: "1")
end
<% end -%>
it "routes to #create" do
expect(post: "/<%= ns_table_name %>").to route_to("<%= ns_table_name %>#create")
end
it "routes to #update via PUT" do
expect(put: "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#update", id: "1")
end
it "routes to #update via PATCH" do
expect(patch: "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#update", id: "1")
end
it "routes to #destroy" do
expect(delete: "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#destroy", id: "1")
end
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/new_spec.rb | lib/generators/rspec/scaffold/templates/new_spec.rb | require 'rails_helper'
<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
RSpec.describe "<%= ns_table_name %>/new", <%= type_metatag(:view) %> do
before(:each) do
assign(:<%= singular_table_name %>, <%= class_name %>.new(<%= '))' if output_attributes.empty? %>
<% output_attributes.each_with_index do |attribute, attribute_index| -%>
<%= attribute.name %>: <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
<% end -%>
<%= !output_attributes.empty? ? " ))\n end" : " end" %>
it "renders new <%= ns_file_name %> form" do
render
assert_select "form[action=?][method=?]", <%= index_helper %>_path, "post" do
<% for attribute in output_attributes -%>
<%- name = attribute.respond_to?(:column_name) ? attribute.column_name : attribute.name %>
assert_select "<%= attribute.input_type -%>[name=?]", "<%= ns_file_name %>[<%= name %>]"
<% end -%>
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/api_request_spec.rb | lib/generators/rspec/scaffold/templates/api_request_spec.rb | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to test the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
<% module_namespacing do -%>
RSpec.describe "/<%= name.underscore.pluralize %>", <%= type_metatag(:request) %> do
# This should return the minimal set of attributes required to create a valid
# <%= class_name %>. As you add validations to <%= class_name %>, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the headers
# in order to pass any filters (e.g. authentication) defined in
# <%= controller_class_name %>Controller, or in your router and rack
# middleware. Be sure to keep this updated too.
let(:valid_headers) {
{}
}
<% unless options[:singleton] -%>
describe "GET /index" do
it "renders a successful response" do
<%= class_name %>.create! valid_attributes
get <%= index_helper %>_url, headers: valid_headers, as: :json
expect(response).to be_successful
end
end
<% end -%>
describe "GET /show" do
it "renders a successful response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get <%= show_helper %>, as: :json
expect(response).to be_successful
end
end
describe "POST /create" do
context "with valid parameters" do
it "creates a new <%= class_name %>" do
expect {
post <%= index_helper %>_url,
params: { <%= singular_table_name %>: valid_attributes }, headers: valid_headers, as: :json
}.to change(<%= class_name %>, :count).by(1)
end
it "renders a JSON response with the new <%= singular_table_name %>" do
post <%= index_helper %>_url,
params: { <%= singular_table_name %>: valid_attributes }, headers: valid_headers, as: :json
expect(response).to have_http_status(:created)
expect(response.content_type).to match(a_string_including("application/json"))
end
end
context "with invalid parameters" do
it "does not create a new <%= class_name %>" do
expect {
post <%= index_helper %>_url,
params: { <%= singular_table_name %>: invalid_attributes }, as: :json
}.to change(<%= class_name %>, :count).by(0)
end
it "renders a JSON response with errors for the new <%= singular_table_name %>" do
post <%= index_helper %>_url,
params: { <%= singular_table_name %>: invalid_attributes }, headers: valid_headers, as: :json
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
expect(response.content_type).to match(a_string_including("application/json"))
end
end
end
describe "PATCH /update" do
context "with valid parameters" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>,
params: { <%= singular_table_name %>: new_attributes }, headers: valid_headers, as: :json
<%= file_name %>.reload
skip("Add assertions for updated state")
end
it "renders a JSON response with the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>,
params: { <%= singular_table_name %>: new_attributes }, headers: valid_headers, as: :json
expect(response).to have_http_status(:ok)
expect(response.content_type).to match(a_string_including("application/json"))
end
end
context "with invalid parameters" do
it "renders a JSON response with errors for the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>,
params: { <%= singular_table_name %>: invalid_attributes }, headers: valid_headers, as: :json
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
expect(response.content_type).to match(a_string_including("application/json"))
end
end
end
describe "DELETE /destroy" do
it "destroys the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
expect {
delete <%= show_helper %>, headers: valid_headers, as: :json
}.to change(<%= class_name %>, :count).by(-1)
end
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/request_spec.rb | lib/generators/rspec/scaffold/templates/request_spec.rb | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to test the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
<% module_namespacing do -%>
RSpec.describe "/<%= name.underscore.pluralize %>", <%= type_metatag(:request) %> do
<% if mountable_engine? -%>
include Engine.routes.url_helpers
<% end -%>
# This should return the minimal set of attributes required to create a valid
# <%= class_name %>. As you add validations to <%= class_name %>, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
<% unless options[:singleton] -%>
describe "GET /index" do
it "renders a successful response" do
<%= class_name %>.create! valid_attributes
get <%= index_helper %>_url
expect(response).to be_successful
end
end
<% end -%>
describe "GET /show" do
it "renders a successful response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get <%= show_helper %>
expect(response).to be_successful
end
end
describe "GET /new" do
it "renders a successful response" do
get <%= new_helper %>
expect(response).to be_successful
end
end
describe "GET /edit" do
it "renders a successful response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get <%= edit_helper %>
expect(response).to be_successful
end
end
describe "POST /create" do
context "with valid parameters" do
it "creates a new <%= class_name %>" do
expect {
post <%= index_helper %>_url, params: { <%= singular_table_name %>: valid_attributes }
}.to change(<%= class_name %>, :count).by(1)
end
it "redirects to the created <%= singular_table_name %>" do
post <%= index_helper %>_url, params: { <%= singular_table_name %>: valid_attributes }
expect(response).to redirect_to(<%= show_helper(class_name+".last") %>)
end
end
context "with invalid parameters" do
it "does not create a new <%= class_name %>" do
expect {
post <%= index_helper %>_url, params: { <%= singular_table_name %>: invalid_attributes }
}.to change(<%= class_name %>, :count).by(0)
end
it "renders a response with 422 status (i.e. to display the 'new' template)" do
post <%= index_helper %>_url, params: { <%= singular_table_name %>: invalid_attributes }
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
end
end
end
describe "PATCH /update" do
context "with valid parameters" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>, params: { <%= singular_table_name %>: new_attributes }
<%= file_name %>.reload
skip("Add assertions for updated state")
end
it "redirects to the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>, params: { <%= singular_table_name %>: new_attributes }
<%= file_name %>.reload
expect(response).to redirect_to(<%= singular_table_name %>_url(<%= file_name %>))
end
end
context "with invalid parameters" do
it "renders a response with 422 status (i.e. to display the 'edit' template)" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
patch <%= show_helper %>, params: { <%= singular_table_name %>: invalid_attributes }
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
end
end
end
describe "DELETE /destroy" do
it "destroys the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
expect {
delete <%= show_helper %>
}.to change(<%= class_name %>, :count).by(-1)
end
it "redirects to the <%= table_name %> list" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
delete <%= show_helper %>
expect(response).to redirect_to(<%= index_helper %>_url)
end
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/controller_spec.rb | lib/generators/rspec/scaffold/templates/controller_spec.rb | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
#
# Also compared to earlier versions of this generator, there are no longer any
# expectations of assigns and templates rendered. These features have been
# removed from Rails core in Rails 5, but can be added back in via the
# `rails-controller-testing` gem.
<% module_namespacing do -%>
RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(:controller) %> do
# This should return the minimal set of attributes required to create a valid
# <%= class_name %>. As you add validations to <%= class_name %>, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# <%= controller_class_name %>Controller. Be sure to keep this updated too.
let(:valid_session) { {} }
<% unless options[:singleton] -%>
describe "GET #index" do
it "returns a success response" do
<%= class_name %>.create! valid_attributes
get :index, params: {}, session: valid_session
expect(response).to be_successful
end
end
<% end -%>
describe "GET #show" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get :show, params: {id: <%= file_name %>.to_param}, session: valid_session
expect(response).to be_successful
end
end
describe "GET #new" do
it "returns a success response" do
get :new, params: {}, session: valid_session
expect(response).to be_successful
end
end
describe "GET #edit" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get :edit, params: {id: <%= file_name %>.to_param}, session: valid_session
expect(response).to be_successful
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new <%= class_name %>" do
expect {
post :create, params: {<%= singular_table_name %>: valid_attributes}, session: valid_session
}.to change(<%= class_name %>, :count).by(1)
end
it "redirects to the created <%= singular_table_name %>" do
post :create, params: {<%= singular_table_name %>: valid_attributes}, session: valid_session
expect(response).to redirect_to(<%= class_name %>.last)
end
end
context "with invalid params" do
it "renders a response with 422 status (i.e. to display the 'new' template)" do
post :create, params: {<%= singular_table_name %>: invalid_attributes}, session: valid_session
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: new_attributes}, session: valid_session
<%= file_name %>.reload
skip("Add assertions for updated state")
end
it "redirects to the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: new_attributes}, session: valid_session
expect(response).to redirect_to(<%= file_name %>)
end
end
context "with invalid params" do
it "renders a response with 422 status (i.e. to display the 'edit' template)" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: invalid_attributes}, session: valid_session
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
end
end
end
describe "DELETE #destroy" do
it "destroys the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
expect {
delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session
}.to change(<%= class_name %>, :count).by(-1)
end
it "redirects to the <%= table_name %> list" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session
expect(response).to redirect_to(<%= index_helper %>_url)
end
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/api_controller_spec.rb | lib/generators/rspec/scaffold/templates/api_controller_spec.rb | require 'rails_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
#
# Also compared to earlier versions of this generator, there are no longer any
# expectations of assigns and templates rendered. These features have been
# removed from Rails core in Rails 5, but can be added back in via the
# `rails-controller-testing` gem.
<% module_namespacing do -%>
RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(:controller) %> do
# This should return the minimal set of attributes required to create a valid
# <%= class_name %>. As you add validations to <%= class_name %>, be sure to
# adjust the attributes here as well.
let(:valid_attributes) {
skip("Add a hash of attributes valid for your model")
}
let(:invalid_attributes) {
skip("Add a hash of attributes invalid for your model")
}
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# <%= controller_class_name %>Controller. Be sure to keep this updated too.
let(:valid_session) { {} }
<% unless options[:singleton] -%>
describe "GET #index" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get :index, params: {}, session: valid_session
expect(response).to be_successful
end
end
<% end -%>
describe "GET #show" do
it "returns a success response" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
get :show, params: {id: <%= file_name %>.to_param}, session: valid_session
expect(response).to be_successful
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new <%= class_name %>" do
expect {
post :create, params: {<%= singular_table_name %>: valid_attributes}, session: valid_session
}.to change(<%= class_name %>, :count).by(1)
end
it "renders a JSON response with the new <%= singular_table_name %>" do
post :create, params: {<%= singular_table_name %>: valid_attributes}, session: valid_session
expect(response).to have_http_status(:created)
expect(response.content_type).to eq('application/json')
expect(response.location).to eq(<%= singular_table_name %>_url(<%= class_name %>.last))
end
end
context "with invalid params" do
it "renders a JSON response with errors for the new <%= singular_table_name %>" do
post :create, params: {<%= singular_table_name %>: invalid_attributes}, session: valid_session
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
expect(response.content_type).to eq('application/json')
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) {
skip("Add a hash of attributes valid for your model")
}
it "updates the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: new_attributes}, session: valid_session
<%= file_name %>.reload
skip("Add assertions for updated state")
end
it "renders a JSON response with the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: new_attributes}, session: valid_session
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/json')
end
end
context "with invalid params" do
it "renders a JSON response with errors for the <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
put :update, params: {id: <%= file_name %>.to_param, <%= singular_table_name %>: invalid_attributes}, session: valid_session
expect(response).to have_http_status(<%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>)
expect(response.content_type).to eq('application/json')
end
end
end
describe "DELETE #destroy" do
it "destroys the requested <%= singular_table_name %>" do
<%= file_name %> = <%= class_name %>.create! valid_attributes
expect {
delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session
}.to change(<%= class_name %>, :count).by(-1)
end
end
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/edit_spec.rb | lib/generators/rspec/scaffold/templates/edit_spec.rb | require 'rails_helper'
<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
RSpec.describe "<%= ns_table_name %>/edit", <%= type_metatag(:view) %> do
let(:<%= singular_table_name %>) {
<%= class_name %>.create!(<%= ')' if output_attributes.empty? %>
<% output_attributes.each_with_index do |attribute, attribute_index| -%>
<%= attribute.name %>: <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
<% end -%>
<%= " )\n" unless output_attributes.empty? -%>
}
before(:each) do
assign(:<%= singular_table_name %>, <%= singular_table_name %>)
end
it "renders the edit <%= ns_file_name %> form" do
render
assert_select "form[action=?][method=?]", <%= ns_file_name %>_path(<%= singular_table_name %>), "post" do
<% for attribute in output_attributes -%>
<%- name = attribute.respond_to?(:column_name) ? attribute.column_name : attribute.name %>
assert_select "<%= attribute.input_type -%>[name=?]", "<%= ns_file_name %>[<%= name %>]"
<% end -%>
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/scaffold/templates/index_spec.rb | lib/generators/rspec/scaffold/templates/index_spec.rb | require 'rails_helper'
<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
RSpec.describe "<%= ns_table_name %>/index", <%= type_metatag(:view) %> do
before(:each) do
assign(:<%= table_name %>, [
<% [1,2].each_with_index do |id, model_index| -%>
<%= class_name %>.create!(<%= output_attributes.empty? ? (model_index == 1 ? ')' : '),') : '' %>
<% output_attributes.each_with_index do |attribute, attribute_index| -%>
<%= attribute.name %>: <%= value_for(attribute) %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
<% end -%>
<% if !output_attributes.empty? -%>
<%= model_index == 1 ? ')' : '),' %>
<% end -%>
<% end -%>
])
end
it "renders a list of <%= ns_table_name %>" do
render
<% if Rails.version.to_f < 8.1 -%>
cell_selector = 'div>p'
<% else -%>
cell_selector = 'div>div>div'
<% end -%>
<% for attribute in output_attributes -%>
assert_select cell_selector, text: Regexp.new(<%= value_for(attribute) %>.to_s), count: 2
<% end -%>
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/mailer/mailer_generator.rb | lib/generators/rspec/mailer/mailer_generator.rb | require 'generators/rspec'
require "rspec/rails/feature_check"
module Rspec
module Generators
# @private
class MailerGenerator < Base
argument :actions, type: :array, default: [], banner: "method method"
def generate_mailer_spec
file_suffix = file_name.end_with?('mailer') ? 'spec.rb' : 'mailer_spec.rb'
template "mailer_spec.rb", target_path('mailers', class_path, [file_name, file_suffix].join('_'))
end
def generate_fixtures_files
actions.each do |action|
@action, @path = action, File.join(file_path, action)
template "fixture", target_path("fixtures", @path)
end
end
def generate_preview_files
return unless RSpec::Rails::FeatureCheck.has_action_mailer_preview?
file_suffix = file_name.end_with?('mailer') ? 'preview.rb' : 'mailer_preview.rb'
template "preview.rb", target_path("mailers/previews", class_path, [file_name, file_suffix].join('_'))
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/mailer/templates/preview.rb | lib/generators/rspec/mailer/templates/preview.rb | <% module_namespacing do -%>
# Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %>_mailer
class <%= class_name %><%= 'Mailer' unless class_name.end_with?('Mailer') %>Preview < ActionMailer::Preview
<% actions.each do |action| -%>
# Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>_mailer/<%= action %>
def <%= action %>
<%= class_name.sub(/(Mailer)?$/, 'Mailer') %>.<%= action %>
end
<% end -%>
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/mailer/templates/mailer_spec.rb | lib/generators/rspec/mailer/templates/mailer_spec.rb | require "rails_helper"
<% module_namespacing do -%>
RSpec.describe <%= class_name.sub(/(Mailer)?$/, 'Mailer') %>, <%= type_metatag(:mailer) %> do
<% for action in actions -%>
describe "<%= action %>" do
let(:mail) { <%= class_name.sub(/(Mailer)?$/, 'Mailer') %>.<%= action %> }
it "renders the headers" do
expect(mail.subject).to eq(<%= action.to_s.humanize.inspect %>)
expect(mail.to).to eq(["to@example.org"])
expect(mail.from).to eq(["from@example.com"])
end
it "renders the body" do
expect(mail.body.encoded).to match("Hi")
end
end
<% end -%>
<% if actions.blank? -%>
pending "add some examples to (or delete) #{__FILE__}"
<% end -%>
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/model/model_generator.rb | lib/generators/rspec/model/model_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class ModelGenerator < Base
argument :attributes,
type: :array,
default: [],
banner: "field:type field:type"
class_option :fixture, type: :boolean
def create_model_spec
template_file = target_path(
'models',
class_path,
"#{file_name}_spec.rb"
)
template 'model_spec.rb', template_file
end
hook_for :fixture_replacement
def create_fixture_file
return unless missing_fixture_replacement?
template 'fixtures.yml', target_path('fixtures', class_path, "#{(pluralize_table_names? ? plural_file_name : file_name)}.yml")
end
private
def missing_fixture_replacement?
options[:fixture] && options[:fixture_replacement].nil?
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/model/templates/model_spec.rb | lib/generators/rspec/model/templates/model_spec.rb | require 'rails_helper'
<% module_namespacing do -%>
RSpec.describe <%= class_name %>, <%= type_metatag(:model) %> do
pending "add some examples to (or delete) #{__FILE__}"
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/authentication/authentication_generator.rb | lib/generators/rspec/authentication/authentication_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class AuthenticationGenerator < Base
def initialize(args, *options)
args.replace(['User'])
super
end
def create_user_spec
template 'user_spec.rb', target_path('models', 'user_spec.rb')
end
hook_for :fixture_replacement
def create_fixture_file
return if options[:fixture_replacement]
template 'users.yml', target_path('fixtures', 'users.yml')
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/authentication/templates/user_spec.rb | lib/generators/rspec/authentication/templates/user_spec.rb | require 'rails_helper'
RSpec.describe User, <%= type_metatag(:model) %> do
pending "add some examples to (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/generator/generator_generator.rb | lib/generators/rspec/generator/generator_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class GeneratorGenerator < Base
class_option :generator_specs, type: :boolean, default: true, desc: 'Generate generator specs'
def generate_generator_spec
return unless options[:generator_specs]
template template_name, target_path('generator', class_path, filename)
end
def template_name
'generator_spec.rb'
end
def filename
"#{file_name}_generator_spec.rb"
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/generator/templates/generator_spec.rb | lib/generators/rspec/generator/templates/generator_spec.rb | require 'rails_helper'
RSpec.describe "<%= class_name %>Generator", <%= type_metatag(:generator) %> do
pending "add some scenarios (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/feature/feature_generator.rb | lib/generators/rspec/feature/feature_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class FeatureGenerator < Base
class_option :feature_specs, type: :boolean, default: true, desc: "Generate feature specs"
class_option :singularize, type: :boolean, default: false, desc: "Singularize the generated feature"
def generate_feature_spec
return unless options[:feature_specs]
template template_name, target_path('features', class_path, filename)
end
def template_name
options[:singularize] ? 'feature_singular_spec.rb' : 'feature_spec.rb'
end
def filename
if options[:singularize]
"#{file_name.singularize}_spec.rb"
else
"#{file_name}_spec.rb"
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/feature/templates/feature_singular_spec.rb | lib/generators/rspec/feature/templates/feature_singular_spec.rb | require 'rails_helper'
RSpec.feature "<%= class_name.singularize %>", <%= type_metatag(:feature) %> do
pending "add some scenarios (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/feature/templates/feature_spec.rb | lib/generators/rspec/feature/templates/feature_spec.rb | require 'rails_helper'
RSpec.feature "<%= class_name.pluralize %>", <%= type_metatag(:feature) %> do
pending "add some scenarios (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/view/view_generator.rb | lib/generators/rspec/view/view_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class ViewGenerator < Base
argument :actions, type: :array, default: [], banner: "action action"
class_option :template_engine, desc: "Template engine to generate view files"
def create_view_specs
empty_directory target_path("views", file_path)
actions.each do |action|
@action = action
template 'view_spec.rb',
target_path("views", file_path, "#{@action}.html.#{options[:template_engine]}_spec.rb")
end
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/view/templates/view_spec.rb | lib/generators/rspec/view/templates/view_spec.rb | require 'rails_helper'
RSpec.describe "<%= file_path %>/<%= @action %>", <%= type_metatag(:view) %> do
pending "add some examples to (or delete) #{__FILE__}"
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/helper/helper_generator.rb | lib/generators/rspec/helper/helper_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class HelperGenerator < Base
class_option :helper_specs, type: :boolean, default: true
def generate_helper_spec
return unless options[:helper_specs]
template 'helper_spec.rb', target_path('helpers', class_path, "#{file_name}_helper_spec.rb")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/helper/templates/helper_spec.rb | lib/generators/rspec/helper/templates/helper_spec.rb | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the <%= class_name %>Helper. For example:
#
# describe <%= class_name %>Helper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
<% module_namespacing do -%>
RSpec.describe <%= class_name %>Helper, <%= type_metatag(:helper) %> do
pending "add some examples to (or delete) #{__FILE__}"
end
<% end -%>
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/mailbox/mailbox_generator.rb | lib/generators/rspec/mailbox/mailbox_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class MailboxGenerator < Base
def create_mailbox_spec
template('mailbox_spec.rb.erb',
target_path('mailboxes', class_path, "#{file_name}_mailbox_spec.rb")
)
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/channel/channel_generator.rb | lib/generators/rspec/channel/channel_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class ChannelGenerator < Base
def create_channel_spec
template 'channel_spec.rb.erb', target_path('channels', class_path, "#{file_name}_channel_spec.rb")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
rspec/rspec-rails | https://github.com/rspec/rspec-rails/blob/f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df/lib/generators/rspec/request/request_generator.rb | lib/generators/rspec/request/request_generator.rb | require 'generators/rspec'
module Rspec
module Generators
# @private
class RequestGenerator < Base
class_option :request_specs, type: :boolean, default: true, desc: 'Generate request specs'
def generate_request_spec
return unless options[:request_specs]
template 'request_spec.rb',
target_path('requests', "#{name.underscore.pluralize}_spec.rb")
end
end
end
end
| ruby | MIT | f16a1639b5c2af5cde1ad1682b5c7a4af7f7b3df | 2026-01-04T15:43:26.158415Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.