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 |
|---|---|---|---|---|---|---|---|---|
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/log/console_adapter.rb | lib/fluent/log/console_adapter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'console'
module Fluent
class Log
# Async gem which is used by http_server helper switched logger mechanism to
# Console gem which isn't compatible with Ruby's standard Logger (since
# v1.17). This class adapts it to Fluentd's logger mechanism.
class ConsoleAdapter < Console::Output::Terminal
def self.wrap(logger)
_, level = Console::Logger::LEVELS.find { |key, value|
if logger.level <= 0
key == :debug
else
value == logger.level - 1
end
}
Console::Logger.new(ConsoleAdapter.new(logger), level: level)
end
def initialize(logger)
@logger = logger
# When `verbose` is `true`, following items will be added as a prefix or
# suffix of the subject:
# * Severity
# * Object ID
# * PID
# * Time
# Severity and Time are added by Fluentd::Log too so they are redundant.
# PID is the worker's PID so it's also redundant.
# Object ID will be too verbose in usual cases.
# So set it as `false` here to suppress redundant items.
super(StringIO.new, verbose: false)
end
def call(subject = nil, *arguments, name: nil, severity: 'info', **options, &block)
if LEVEL_TEXT.include?(severity.to_s)
level = severity
else
@logger.warn("Unknown severity: #{severity}")
level = 'warn'
end
@stream.seek(0)
@stream.truncate(0)
super
@logger.send(level, @stream.string.chomp)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/init.rb | init.rb | require 'resque'
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque_hook_test.rb | test/resque_hook_test.rb | require 'test_helper'
require 'tempfile'
describe "Resque Hooks" do
class CallNotifyJob
def self.perform
$called = true
end
end
before do
$called = false
@worker = Resque::Worker.new(:jobs)
end
it 'retrieving hooks if none have been set' do
assert_equal [], Resque.before_first_fork
assert_equal [], Resque.before_fork
assert_equal [], Resque.after_fork
end
it 'it calls before_first_fork once' do
counter = 0
Resque.before_first_fork { counter += 1 }
2.times { Resque::Job.create(:jobs, CallNotifyJob) }
assert_equal(0, counter)
@worker.work(0)
assert_equal(1, counter)
end
it 'it calls before_fork before each job' do
file = Tempfile.new("resque_before_fork") # to share state with forked process
begin
File.open(file.path, "w") {|f| f.write(0)}
Resque.before_fork do
val = File.read(file).strip.to_i
File.open(file.path, "w") {|f| f.write(val + 1)}
end
2.times { Resque::Job.create(:jobs, CallNotifyJob) }
val = File.read(file.path).strip.to_i
assert_equal(0, val)
@worker.work(0)
val = File.read(file.path).strip.to_i
assert_equal(2, val)
ensure
file.delete
end
end
it 'it calls after_fork after each job' do
file = Tempfile.new("resque_after_fork") # to share state with forked process
begin
File.open(file.path, "w") {|f| f.write(0)}
Resque.after_fork do
val = File.read(file).strip.to_i
File.open(file.path, "w") {|f| f.write(val + 1)}
end
2.times { Resque::Job.create(:jobs, CallNotifyJob) }
val = File.read(file.path).strip.to_i
assert_equal(0, val)
@worker.work(0)
val = File.read(file.path).strip.to_i
assert_equal(2, val)
ensure
file.delete
end
end
it 'it calls before_first_fork before forking' do
Resque.before_first_fork { assert(!$called) }
Resque::Job.create(:jobs, CallNotifyJob)
@worker.work(0)
end
it 'it calls before_fork before forking' do
Resque.before_fork { assert(!$called) }
Resque::Job.create(:jobs, CallNotifyJob)
@worker.work(0)
end
it 'it calls after_fork after forking' do
Resque.after_fork { assert($called) }
Resque::Job.create(:jobs, CallNotifyJob)
@worker.work(0)
end
it 'it registers multiple before_first_forks' do
first = false
second = false
Resque.before_first_fork { first = true }
Resque.before_first_fork { second = true }
Resque::Job.create(:jobs, CallNotifyJob)
assert(!first && !second)
@worker.work(0)
assert(first && second)
end
it 'it registers multiple before_forks' do
# use tempfiles to share state with forked process
file = Tempfile.new("resque_before_fork_first")
file2 = Tempfile.new("resque_before_fork_second")
begin
File.open(file.path, "w") {|f| f.write(1)}
File.open(file2.path, "w") {|f| f.write(2)}
Resque.before_fork do
val = File.read(file.path).strip.to_i
File.open(file.path, "w") {|f| f.write(val + 1)}
end
Resque.before_fork do
val = File.read(file2.path).strip.to_i
File.open(file2.path, "w") {|f| f.write(val + 1)}
end
Resque::Job.create(:jobs, CallNotifyJob)
@worker.work(0)
val = File.read(file.path).strip.to_i
val2 = File.read(file2.path).strip.to_i
assert_equal(val, 2)
assert_equal(val2, 3)
ensure
file.delete
file2.delete
end
end
it 'it registers multiple after_forks' do
# use tempfiles to share state with forked process
file = Tempfile.new("resque_after_fork_first")
file2 = Tempfile.new("resque_after_fork_second")
begin
File.open(file.path, "w") {|f| f.write(1)}
File.open(file2.path, "w") {|f| f.write(2)}
Resque.after_fork do
val = File.read(file.path).strip.to_i
File.open(file.path, "w") {|f| f.write(val + 1)}
end
Resque.after_fork do
val = File.read(file2.path).strip.to_i
File.open(file2.path, "w") {|f| f.write(val + 1)}
end
Resque::Job.create(:jobs, CallNotifyJob)
@worker.work(0)
val = File.read(file.path).strip.to_i
val2 = File.read(file2.path).strip.to_i
assert_equal(val, 2)
assert_equal(val2, 3)
ensure
file.delete
file2.delete
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque_failure_multiple_test.rb | test/resque_failure_multiple_test.rb | require 'test_helper'
require 'resque/failure/multiple'
describe 'Resque::Failure::Multiple' do
it 'requeue_all and does not raise an exception' do
with_failure_backend(Resque::Failure::Multiple) do
Resque::Failure::Multiple.classes = [Resque::Failure::Redis]
exception = StandardError.exception('some error')
worker = Resque::Worker.new(:test)
payload = { 'class' => 'Object', 'args' => 3 }
Resque::Failure.create({:exception => exception, :worker => worker, :queue => 'queue', :payload => payload})
Resque::Failure::Multiple.requeue_all # should not raise an error
end
end
it 'requeue_queue delegates to the first class and returns a mapped queue name' do
with_failure_backend(Resque::Failure::Multiple) do
mock_class = Minitest::Mock.new
mock_class.expect(:requeue_queue, 'mapped_queue', ['queue'])
Resque::Failure::Multiple.classes = [mock_class]
assert_equal 'mapped_queue', Resque::Failure::Multiple.requeue_queue('queue')
end
end
it 'remove passes the queue on to its backend' do
with_failure_backend(Resque::Failure::Multiple) do
mock = Object.new
def mock.remove(_id, queue)
@queue = queue
end
Resque::Failure::Multiple.classes = [mock]
Resque::Failure::Multiple.remove(1, :test_queue)
assert_equal :test_queue, mock.instance_variable_get('@queue')
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque_test.rb | test/resque_test.rb | require 'test_helper'
describe "Resque" do
before do
@original_redis = Resque.redis
@original_stat_data_store = Resque.stat_data_store
end
after do
Resque.redis = @original_redis
Resque.stat_data_store = @original_stat_data_store
end
it "can push an item that depends on redis for encoding" do
Resque.redis.set("count", 1)
# No error should be raised
Resque.push(:test, JsonObject.new)
Resque.redis.del("count")
end
it "can set a namespace through a url-like string" do
assert Resque.redis
assert_equal :resque, Resque.redis.namespace
Resque.redis = 'localhost:9736/namespace'
assert_equal 'namespace', Resque.redis.namespace
end
it "redis= works correctly with a Redis::Namespace param" do
new_redis = Redis.new(:host => "localhost", :port => 9736)
new_namespace = Redis::Namespace.new("namespace", :redis => new_redis)
Resque.redis = new_namespace
assert_equal new_namespace._client, Resque.redis._client
assert_equal 0, Resque.size(:default)
end
it "can put jobs on a queue" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
end
it "can grab jobs off a queue" do
Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
job = Resque.reserve(:jobs)
assert_kind_of Resque::Job, job
assert_equal SomeJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
end
it "can re-queue jobs" do
Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
job = Resque.reserve(:jobs)
job.recreate
assert_equal job, Resque.reserve(:jobs)
end
it "can put jobs on a queue by way of an ivar" do
assert_equal 0, Resque.size(:ivar)
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
job = Resque.reserve(:ivar)
assert_kind_of Resque::Job, job
assert_equal SomeIvarJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
assert Resque.reserve(:ivar)
assert_nil Resque.reserve(:ivar)
end
it "can remove jobs from a queue by way of an ivar" do
assert_equal 0, Resque.size(:ivar)
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 30, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque::Job.create(:ivar, 'blah-job', 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert_equal 5, Resque.size(:ivar)
assert_equal 1, Resque.dequeue(SomeIvarJob, 30, '/tmp')
assert_equal 4, Resque.size(:ivar)
assert_equal 3, Resque.dequeue(SomeIvarJob)
assert_equal 1, Resque.size(:ivar)
end
it "jobs have a nice #inspect" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
job = Resque.reserve(:jobs)
assert_equal '(Job{jobs} | SomeJob | [20, "/tmp"])', job.inspect
end
it "jobs can be destroyed" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 30, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 20, '/tmp')
assert_equal 5, Resque.size(:jobs)
assert_equal 2, Resque::Job.destroy(:jobs, 'SomeJob')
assert_equal 3, Resque.size(:jobs)
assert_equal 1, Resque::Job.destroy(:jobs, 'BadJob', 30, '/tmp')
assert_equal 2, Resque.size(:jobs)
end
it "jobs can it for equality" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
assert_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
assert Resque::Job.create(:jobs, 'SomeMethodJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
refute_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 30, '/tmp')
refute_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
end
it "can put jobs on a queue by way of a method" do
assert_equal 0, Resque.size(:method)
assert Resque.enqueue(SomeMethodJob, 20, '/tmp')
assert Resque.enqueue(SomeMethodJob, 20, '/tmp')
job = Resque.reserve(:method)
assert_kind_of Resque::Job, job
assert_equal SomeMethodJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
assert Resque.reserve(:method)
assert_nil Resque.reserve(:method)
end
it "can define a queue for jobs by way of a method" do
assert_equal 0, Resque.size(:method)
assert Resque.enqueue_to(:new_queue, SomeMethodJob, 20, '/tmp')
job = Resque.reserve(:new_queue)
assert_equal SomeMethodJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
end
it "needs to infer a queue with enqueue" do
assert_raises Resque::NoQueueError do
Resque.enqueue(SomeJob, 20, '/tmp')
end
end
it "validates job for queue presence" do
err = assert_raises Resque::NoQueueError do
Resque.validate(SomeJob)
end
assert_match(/SomeJob/, err.message)
end
it "can put items on a queue" do
assert Resque.push(:people, { 'name' => 'jon' })
end
it "queues are always a list" do
assert_equal [], Resque.queues
end
it "badly wants a class name, too" do
assert_raises Resque::NoClassError do
Resque::Job.create(:jobs, nil)
end
end
it "decode bad json" do
assert_raises Resque::Helpers::DecodeException do
Resque.decode("{\"error\":\"Module not found \\u002\"}")
end
end
it "inlining jobs" do
begin
Resque.inline = true
Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert_equal 0, Resque.size(:ivar)
ensure
Resque.inline = false
end
end
describe "with people in the queue" do
before do
Resque.push(:people, { 'name' => 'chris' })
Resque.push(:people, { 'name' => 'bob' })
Resque.push(:people, { 'name' => 'mark' })
end
it "can pull items off a queue" do
assert_equal({ 'name' => 'chris' }, Resque.pop(:people))
assert_equal({ 'name' => 'bob' }, Resque.pop(:people))
assert_equal({ 'name' => 'mark' }, Resque.pop(:people))
assert_nil Resque.pop(:people)
end
it "knows how big a queue is" do
assert_equal 3, Resque.size(:people)
assert_equal({ 'name' => 'chris' }, Resque.pop(:people))
assert_equal 2, Resque.size(:people)
assert_equal({ 'name' => 'bob' }, Resque.pop(:people))
assert_equal({ 'name' => 'mark' }, Resque.pop(:people))
assert_equal 0, Resque.size(:people)
end
it "can peek at a queue" do
assert_equal({ 'name' => 'chris' }, Resque.peek(:people))
assert_equal 3, Resque.size(:people)
end
it "can peek multiple items on a queue" do
assert_equal({ 'name' => 'bob' }, Resque.peek(:people, 1, 1))
assert_equal([{ 'name' => 'bob' }, { 'name' => 'mark' }], Resque.peek(:people, 1, 2))
assert_equal([{ 'name' => 'chris' }, { 'name' => 'bob' }], Resque.peek(:people, 0, 2))
assert_equal([{ 'name' => 'chris' }, { 'name' => 'bob' }, { 'name' => 'mark' }], Resque.peek(:people, 0, 3))
assert_equal({ 'name' => 'mark' }, Resque.peek(:people, 2, 1))
assert_nil Resque.peek(:people, 3)
assert_equal [], Resque.peek(:people, 3, 2)
end
it "can delete a queue" do
Resque.push(:cars, { 'make' => 'bmw' })
assert_equal %w( cars people ).sort, Resque.queues.sort
Resque.remove_queue(:people)
assert_equal %w( cars ), Resque.queues
assert_nil Resque.pop(:people)
end
it "knows what queues it is managing" do
assert_equal %w( people ), Resque.queues
Resque.push(:cars, { 'make' => 'bmw' })
assert_equal %w( cars people ).sort, Resque.queues.sort
end
it "keeps track of resque keys" do
# ignore the heartbeat key that gets set in a background thread
keys = Resque.keys - ['workers:heartbeat']
assert_equal ["queue:people", "queues"].sort, keys.sort
end
it "keeps stats" do
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
Resque::Job.create(:jobs, BadJob)
Resque::Job.create(:jobs, GoodJob)
Resque::Job.create(:others, GoodJob)
Resque::Job.create(:others, GoodJob)
stats = Resque.info
assert_equal 8, stats[:pending]
@worker = Resque::Worker.new(:jobs)
@worker.register_worker
2.times { @worker.process }
job = @worker.reserve
@worker.working_on job
stats = Resque.info
assert_equal 1, stats[:working]
assert_equal 1, stats[:workers]
@worker.done_working
stats = Resque.info
assert_equal 3, stats[:queues]
assert_equal 3, stats[:processed]
assert_equal 1, stats[:failed]
assert_equal [Resque.redis_id], stats[:servers]
end
end
describe "stats" do
it "allows to set custom stat_data_store" do
dummy = Object.new
Resque.stat_data_store = dummy
assert_equal dummy, Resque.stat_data_store
end
it "queue_sizes with one queue" do
Resque.enqueue_to(:queue1, SomeJob)
queue_sizes = Resque.queue_sizes
assert_equal({ "queue1" => 1 }, queue_sizes)
end
it "queue_sizes with two queue" do
Resque.enqueue_to(:queue1, SomeJob)
Resque.enqueue_to(:queue2, SomeJob)
queue_sizes = Resque.queue_sizes
assert_equal({ "queue1" => 1, "queue2" => 1, }, queue_sizes)
end
it "queue_sizes with two queue with multiple jobs" do
5.times { Resque.enqueue_to(:queue1, SomeJob) }
9.times { Resque.enqueue_to(:queue2, SomeJob) }
queue_sizes = Resque.queue_sizes
assert_equal({ "queue1" => 5, "queue2" => 9 }, queue_sizes)
end
it "sample_queues with simple job with no args" do
Resque.enqueue_to(:queue1, SomeJob)
queues = Resque.sample_queues
assert_equal 1, queues.length
assert_instance_of Hash, queues['queue1']
assert_equal 1, queues['queue1'][:size]
samples = queues['queue1'][:samples]
assert_equal "SomeJob", samples[0]['class']
assert_equal([], samples[0]['args'])
end
it "sample_queues with simple job with args" do
Resque.enqueue_to(:queue1, SomeJob, :arg1 => '1')
queues = Resque.sample_queues
assert_equal 1, queues['queue1'][:size]
samples = queues['queue1'][:samples]
assert_equal "SomeJob", samples[0]['class']
assert_equal([{'arg1' => '1'}], samples[0]['args'])
end
it "sample_queues with simple jobs" do
Resque.enqueue_to(:queue1, SomeJob, :arg1 => '1')
Resque.enqueue_to(:queue1, SomeJob, :arg1 => '2')
queues = Resque.sample_queues
assert_equal 2, queues['queue1'][:size]
samples = queues['queue1'][:samples]
assert_equal([{'arg1' => '1'}], samples[0]['args'])
assert_equal([{'arg1' => '2'}], samples[1]['args'])
end
it "sample_queues with more jobs only returns sample size number of jobs" do
11.times { Resque.enqueue_to(:queue1, SomeJob) }
queues = Resque.sample_queues(10)
assert_equal 11, queues['queue1'][:size]
samples = queues['queue1'][:samples]
assert_equal 10, samples.count
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/airbrake_test.rb | test/airbrake_test.rb |
require 'test_helper'
begin
require 'airbrake'
rescue LoadError
warn "Install airbrake gem to run Airbrake tests."
end
if defined? Airbrake::AIRBRAKE_VERSION
require 'resque/failure/airbrake'
describe "Airbrake" do
it "should be notified of an error" do
exception = StandardError.new("BOOM")
worker = Resque::Worker.new(:test)
queue = "test"
payload = {'class' => Object, 'args' => 66}
notify_method =
if Airbrake::AIRBRAKE_VERSION.to_i < 5
:notify
else
:notify_sync
end
Airbrake.expects(notify_method).with(
exception,
:parameters => {:payload_class => 'Object', :payload_args => '66'})
backend = Resque::Failure::Airbrake.new(exception, worker, queue, payload)
backend.save
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/failure_base_test.rb | test/failure_base_test.rb | require 'test_helper'
require 'minitest/mock'
require 'resque/failure/base'
class TestFailure < Resque::Failure::Base
end
describe "Base failure class" do
it "allows calling all without throwing" do
with_failure_backend TestFailure do
assert_empty Resque::Failure.all
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque-web_test.rb | test/resque-web_test.rb | require 'test_helper'
require 'rack/test'
require 'resque/server'
describe "Resque web" do
include Rack::Test::Methods
def app
Resque::Server.new
end
def default_host
'localhost'
end
# Root path test
describe "on GET to /" do
before { get "/" }
it "redirect to overview" do
follow_redirect!
end
end
# Global overview
describe "on GET to /overview" do
before { get "/overview" }
it "should at least display 'queues'" do
assert last_response.body.include?('Queues')
end
end
describe "With append-prefix option on GET to /overview" do
reverse_proxy_prefix = 'proxy_site/resque'
Resque::Server.url_prefix = reverse_proxy_prefix
before { get "/overview" }
it "should contain reverse proxy prefix for asset urls and links" do
assert last_response.body.include?(reverse_proxy_prefix)
end
end
# Working jobs
describe "on GET to /working" do
before { get "/working" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
# Queues
describe "on GET to /queues" do
before { Resque::Failure.stubs(:count).returns(1) }
describe "with Resque::Failure::RedisMultiQueue backend enabled" do
it "should display failed queues" do
with_failure_backend Resque::Failure::RedisMultiQueue do
Resque::Failure.stubs(:queues).returns(
[:queue1_failed, :queue2_failed]
)
get "/queues"
end
assert last_response.body.include?('queue1_failed')
assert last_response.body.include?('queue2_failed')
end
it "should respond with success when no failed queues exists" do
with_failure_backend Resque::Failure::RedisMultiQueue do
Resque::Failure.stubs(:queues).returns([])
get "/queues"
end
assert last_response.ok?, last_response.errors
end
end
describe "Without Resque::Failure::RedisMultiQueue backend enabled" do
it "should display queues when there are more than 1 failed queue" do
Resque::Failure.stubs(:queues).returns(
[:queue1_failed, :queue2_failed]
)
get "/queues"
assert last_response.body.include?('queue1_failed')
assert last_response.body.include?('queue2_failed')
end
it "should display 'failed' queue when there is 1 failed queue" do
Resque::Failure.stubs(:queues).returns([:queue1])
get "/queues"
assert !last_response.body.include?('queue1')
assert last_response.body.include?('failed')
end
it "should respond with success when no failed queues exists" do
Resque::Failure.stubs(:queues).returns([])
get "/queues"
assert last_response.ok?, last_response.errors
end
end
end
# Failed
describe "on GET to /failed" do
before { get "/failed" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
# Stats
describe "on GET to /stats/resque" do
before { get "/stats/resque" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
describe "on GET to /stats/redis" do
before { get "/stats/redis" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
describe "on GET to /stats/resque" do
before { get "/stats/keys" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
describe "also works with slash at the end" do
before { get "/working/" }
it "should respond with success" do
assert last_response.ok?, last_response.errors
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/logging_test.rb | test/logging_test.rb | require 'test_helper'
require 'minitest/mock'
describe "Resque::Logging" do
it "sets and receives the active logger" do
my_logger = Object.new
Resque.logger = my_logger
assert_equal my_logger, Resque.logger
end
%w(debug info error fatal).each do |severity|
it "logs #{severity} messages" do
message = "test message"
mock_logger = Minitest::Mock.new
mock_logger.expect severity.to_sym, nil, [message]
Resque.logger = mock_logger
Resque::Logging.send severity, message
mock_logger.verify
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/plugin_test.rb | test/plugin_test.rb | require 'test_helper'
describe "Resque::Plugin finding hooks" do
module SimplePlugin
extend self
def before_perform1; end
def before_perform; end
def before_perform2; end
def after_perform1; end
def after_perform; end
def after_perform2; end
def perform; end
def around_perform1; end
def around_perform; end
def around_perform2; end
def on_failure1; end
def on_failure; end
def on_failure2; end
end
module HookBlacklistJob
extend self
def around_perform_blacklisted; end
def around_perform_ok; end
def hooks
@hooks ||= Resque::Plugin.job_methods(self) - ['around_perform_blacklisted']
end
end
it "before_perform hooks are found and sorted" do
assert_equal ["before_perform", "before_perform1", "before_perform2"], Resque::Plugin.before_hooks(SimplePlugin).map {|m| m.to_s}
end
it "after_perform hooks are found and sorted" do
assert_equal ["after_perform", "after_perform1", "after_perform2"], Resque::Plugin.after_hooks(SimplePlugin).map {|m| m.to_s}
end
it "around_perform hooks are found and sorted" do
assert_equal ["around_perform", "around_perform1", "around_perform2"], Resque::Plugin.around_hooks(SimplePlugin).map {|m| m.to_s}
end
it "on_failure hooks are found and sorted" do
assert_equal ["on_failure", "on_failure1", "on_failure2"], Resque::Plugin.failure_hooks(SimplePlugin).map {|m| m.to_s}
end
it 'uses job.hooks if available get hook methods' do
assert_equal ['around_perform_ok'], Resque::Plugin.around_hooks(HookBlacklistJob)
end
end
describe "Resque::Plugin linting" do
module ::BadBefore
def self.before_perform; end
end
module ::BadAfter
def self.after_perform; end
end
module ::BadAround
def self.around_perform; end
end
module ::BadFailure
def self.on_failure; end
end
it "before_perform must be namespaced" do
begin
Resque::Plugin.lint(BadBefore)
assert false, "should have failed"
rescue Resque::Plugin::LintError => e
assert_equal "BadBefore.before_perform is not namespaced", e.message
end
end
it "after_perform must be namespaced" do
begin
Resque::Plugin.lint(BadAfter)
assert false, "should have failed"
rescue Resque::Plugin::LintError => e
assert_equal "BadAfter.after_perform is not namespaced", e.message
end
end
it "around_perform must be namespaced" do
begin
Resque::Plugin.lint(BadAround)
assert false, "should have failed"
rescue Resque::Plugin::LintError => e
assert_equal "BadAround.around_perform is not namespaced", e.message
end
end
it "on_failure must be namespaced" do
begin
Resque::Plugin.lint(BadFailure)
assert false, "should have failed"
rescue Resque::Plugin::LintError => e
assert_equal "BadFailure.on_failure is not namespaced", e.message
end
end
module GoodBefore
def self.before_perform1; end
end
module GoodAfter
def self.after_perform1; end
end
module GoodAround
def self.around_perform1; end
end
module GoodFailure
def self.on_failure1; end
end
it "before_perform1 is an ok name" do
Resque::Plugin.lint(GoodBefore)
end
it "after_perform1 is an ok name" do
Resque::Plugin.lint(GoodAfter)
end
it "around_perform1 is an ok name" do
Resque::Plugin.lint(GoodAround)
end
it "on_failure1 is an ok name" do
Resque::Plugin.lint(GoodFailure)
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/test_helper.rb | test/test_helper.rb | require 'rubygems'
require 'bundler/setup'
require 'minitest/autorun'
require 'redis/namespace'
require 'mocha/minitest'
require 'tempfile'
$dir = File.dirname(File.expand_path(__FILE__))
$LOAD_PATH.unshift $dir + '/../lib'
ENV['TERM_CHILD'] = "1"
require 'resque'
$TEST_PID=Process.pid
begin
require 'leftright'
rescue LoadError
end
#
# make sure we can run redis
#
if !system("which redis-server")
puts '', "** can't find `redis-server` in your path"
puts "** try running `sudo rake install`"
abort ''
end
#
# start our own redis when the tests start,
# kill it when they end
#
Minitest.after_run do
if Process.pid == $TEST_PID
processes = `ps -A -o pid,command | grep [r]edis-test`.split("\n")
pids = processes.map { |process| process.split(" ")[0] }
puts "Killing test redis server..."
pids.each { |pid| Process.kill("TERM", pid.to_i) }
system("rm -f #{$dir}/dump.rdb #{$dir}/dump-cluster.rdb")
end
end
class GlobalSpecHooks < Minitest::Spec
def setup
super
reset_logger
Resque.redis.redis.flushall
Resque.before_first_fork = nil
Resque.before_fork = nil
Resque.after_fork = nil
Resque.shutdown = nil
end
def teardown
super
Resque::Worker.kill_all_heartbeat_threads
end
register_spec_type(/.*/, self)
end
if ENV.key? 'RESQUE_DISTRIBUTED'
require 'redis/distributed'
puts "Starting redis for testing at localhost:9736 and localhost:9737..."
`redis-server #{$dir}/redis-test.conf`
`redis-server #{$dir}/redis-test-cluster.conf`
r = Redis::Distributed.new(['redis://localhost:9736', 'redis://localhost:9737'])
Resque.redis = Redis::Namespace.new :resque, :redis => r
else
puts "Starting redis for testing at localhost:9736..."
`redis-server #{$dir}/redis-test.conf`
Resque.redis = 'localhost:9736'
end
##
# Helper to perform job classes
#
module PerformJob
def perform_job(klass, *args)
resque_job = Resque::Job.new(:testqueue, 'class' => klass, 'args' => args)
resque_job.perform
end
end
##
# Helper to make Minitest::Assertion exceptions work properly
# in the block given to Resque::Worker#work.
#
module AssertInWorkBlock
# if a block is given, ensure that it is run, and that any assertion
# failures that occur inside it propagate up to the test.
def work(*args, &block)
return super unless block_given?
ex = catch(:exception_in_block) do
block_called = nil
retval = super(*args) do |*bargs|
begin
block_called = true
block.call(*bargs)
rescue Minitest::Assertion => ex
throw :exception_in_block, ex
end
end
raise "assertion block not called!" unless block_called
return retval
end
ex && raise(ex)
end
end
#
# fixture classes
#
class SomeJob
def self.perform(repo_id, path)
end
end
class JsonObject
def to_json(opts = {})
val = Resque.redis.get("count")
{ "val" => val }.to_json
end
end
class SomeIvarJob < SomeJob
@queue = :ivar
end
class SomeMethodJob < SomeJob
def self.queue
:method
end
end
class BadJob
def self.perform
raise "Bad job!"
end
end
class GoodJob
def self.perform(name)
"Good job, #{name}"
end
end
class AtExitJob
def self.perform(filename)
at_exit do
File.open(filename, "w") {|file| file.puts "at_exit"}
end
"at_exit job"
end
end
class BadJobWithSyntaxError
def self.perform
raise SyntaxError, "Extra Bad job!"
end
end
class BadJobWithOnFailureHookFail < BadJobWithSyntaxError
def self.on_failure_fail_hook(*args)
raise RuntimeError.new("This job is just so bad!")
end
end
class BadFailureBackend < Resque::Failure::Base
def save
raise Exception.new("Failure backend error")
end
end
def with_failure_backend(failure_backend, &block)
previous_backend = Resque::Failure.backend
Resque::Failure.backend = failure_backend
yield block
ensure
Resque::Failure.backend = previous_backend
end
require 'time'
class Time
# Thanks, Timecop
class << self
attr_accessor :fake_time
alias_method :now_without_mock_time, :now
def now
fake_time || now_without_mock_time
end
end
self.fake_time = nil
end
# From minitest/unit
def capture_io
require 'stringio'
orig_stdout, orig_stderr = $stdout, $stderr
captured_stdout, captured_stderr = StringIO.new, StringIO.new
$stdout, $stderr = captured_stdout, captured_stderr
yield
return captured_stdout.string, captured_stderr.string
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
def capture_io_with_pipe
orig_stdout, orig_stderr = $stdout, $stderr
stdout_rd, $stdout = IO.pipe
stderr_rd, $stderr = IO.pipe
yield
$stdout.close
$stderr.close
return stdout_rd.read, stderr_rd.read
ensure
$stdout = orig_stdout
$stderr = orig_stderr
end
# Log to log/test.log
def reset_logger
$test_logger ||= MonoLogger.new(File.open(File.expand_path("../../log/test.log", __FILE__), "w"))
Resque.logger = $test_logger
end
def suppress_warnings
old_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = old_verbose
end
def without_forking
orig_fork_per_job = ENV['FORK_PER_JOB']
begin
ENV['FORK_PER_JOB'] = 'false'
yield
ensure
ENV['FORK_PER_JOB'] = orig_fork_per_job
end
end
def with_pidfile
old_pidfile = ENV["PIDFILE"]
begin
file = Tempfile.new("pidfile")
file.close
ENV["PIDFILE"] = file.path
yield
ensure
file.unlink if file
ENV["PIDFILE"] = old_pidfile
end
end
def with_fake_time(time)
old_time = Time.fake_time
Time.fake_time = time
yield
ensure
Time.fake_time = old_time
end
def with_background
old_background = ENV["BACKGROUND"]
begin
ENV["BACKGROUND"] = "true"
yield
ensure
ENV["BACKGROUND"] = old_background
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/rake_test.rb | test/rake_test.rb | require "rake"
require "test_helper"
require "mocha"
describe "rake tasks" do
before do
Rake.application.rake_require "tasks/resque"
end
after do
ENV['QUEUES'] = nil
ENV['VVERBOSE'] = nil
ENV['VERBOSE'] = nil
end
describe 'resque:work' do
it "requires QUEUE environment variable" do
assert_system_exit("set QUEUE env var, e.g. $ QUEUE=critical,high rake resque:work") do
run_rake_task("resque:work")
end
end
it "works when multiple queues specified" do
ENV["QUEUES"] = "high,low"
Resque::Worker.any_instance.expects(:work)
run_rake_task("resque:work")
end
describe 'log output' do
let(:messages) { StringIO.new }
before do
Resque.logger = Logger.new(messages)
Resque.logger.level = Logger::ERROR
Resque.enqueue_to(:jobs, SomeJob, 20, '/tmp')
Resque::Worker.any_instance.stubs(:shutdown?).returns(false, true) # Process one job and then quit
end
it "triggers DEBUG level logging when VVERBOSE is set to 1" do
ENV['VVERBOSE'] = '1'
ENV['QUEUES'] = 'jobs'
run_rake_task("resque:work")
assert_includes messages.string, 'Starting worker' # Include an info level statement
assert_includes messages.string, 'Registered signals' # Includes a debug level statement
end
it "triggers INFO level logging when VERBOSE is set to 1" do
ENV['VERBOSE'] = '1'
ENV['QUEUES'] = 'jobs'
run_rake_task("resque:work")
assert_includes messages.string, 'Starting worker' # Include an info level statement
refute_includes messages.string, 'Registered signals' # Does not a debug level statement
end
end
end
describe 'resque:workers' do
it 'requires COUNT environment variable' do
assert_system_exit("set COUNT env var, e.g. $ COUNT=2 rake resque:workers") do
run_rake_task("resque:workers")
end
end
end
def run_rake_task(name)
Rake::Task[name].reenable
Rake.application.invoke_task(name)
end
def assert_system_exit(expected_message)
begin
capture_io { yield }
fail 'Expected task to abort'
rescue Exception => e
assert_equal e.message, expected_message
assert_equal e.class, SystemExit
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque-web_runner_test.rb | test/resque-web_runner_test.rb | require 'test_helper'
require 'rack/test'
require 'resque/server'
require 'resque/web_runner'
describe 'Resque::WebRunner' do
def get_rackup_or_rack_handler
Resque::WebRunner.get_rackup_or_rack_handler
end
def web_runner(*args)
Resque::WebRunner.any_instance.stubs(:daemonize!).once
rack_server = Resque::JRUBY ? 'webrick' : 'puma'
get_rackup_or_rack_handler.get(rack_server).stubs(:run).once
@runner = Resque::WebRunner.new(*args)
end
before do
ENV['RESQUECONFIG'] = 'examples/resque_config.rb'
FileUtils.rm_rf(File.join(File.dirname(__FILE__), 'tmp'))
@log = StringIO.new
Resque::WebRunner.logger = Logger.new(@log)
end
describe 'creating an instance' do
describe 'basic usage' do
before do
Resque::WebRunner.any_instance.expects(:system).once
web_runner("route","--debug", sessions: true)
end
it "sets app" do
assert_equal @runner.app, Resque::Server
end
it "sets app name" do
assert_equal @runner.app_name, 'resque-web'
assert_equal @runner.filesystem_friendly_app_name, 'resque_web'
end
it "stores options" do
assert @runner.options[:sessions]
end
it "puts unparsed args into args" do
assert_equal @runner.args, ["route"]
end
it "parses options into @options" do
assert @runner.options[:debug]
end
it "writes the app dir" do
assert File.exist?(@runner.app_dir)
end
it "writes a url with the port" do
assert File.exist?(@runner.url_file)
assert File.read(@runner.url_file).match(/0.0.0.0\:#{@runner.port}/)
end
it "knows where to find the pid file" do
assert_equal @runner.pid_file, \
File.join(@runner.app_dir, @runner.filesystem_friendly_app_name + ".pid")
# assert File.exist?(@runner.pid_file), "#{@runner.pid_file} not found."
end
end
describe 'with a sinatra app using an explicit server setting' do
def web_runner(*args)
Resque::WebRunner.any_instance.stubs(:daemonize!).once
get_rackup_or_rack_handler.get('webrick').stubs(:run).once
@runner = Resque::WebRunner.new(*args)
end
before do
Resque::Server.set :server, "webrick"
get_rackup_or_rack_handler.get('webrick').stubs(:run)
web_runner("route","--debug", skip_launch: true, sessions: true)
end
after do
Resque::Server.set :server, false
end
it 'sets the rack handler automatically' do
assert_equal @runner.rack_handler, get_rackup_or_rack_handler.get('webrick')
end
end
describe 'with a sinatra app without an explicit server setting' do
def web_runner(*args)
Resque::WebRunner.any_instance.stubs(:daemonize!).once
get_rackup_or_rack_handler.get('webrick').stubs(:run).once
@runner = Resque::WebRunner.new(*args)
end
before do
Resque::Server.set :server, ["invalid", "webrick", "puma"]
get_rackup_or_rack_handler.get('webrick').stubs(:run)
web_runner("route", "--debug", skip_launch: true, sessions: true)
end
after do
Resque::Server.set :server, false
end
it 'sets the first valid rack handler' do
assert_equal @runner.rack_handler, get_rackup_or_rack_handler.get('webrick')
end
end
describe 'with a sinatra app without available server settings' do
before do
Resque::Server.set :server, ["invalid"]
end
after do
Resque::Server.set :server, false
end
it 'raises an error indicating that no available Rack handler was found' do
err = assert_raises StandardError do
Resque::WebRunner.new(skip_launch: true, sessions: true)
end
assert_match('No available Rack handler (e.g. WEBrick, Puma, etc.) was found.', err.message)
end
end
describe 'with a simple rack app' do
before do
web_runner(skip_launch: true, sessions: true)
end
it "sets default rack handler to puma when in ruby and WEBrick when in jruby" do
if Resque::JRUBY
assert_equal @runner.rack_handler, get_rackup_or_rack_handler.get('webrick')
else
assert_equal @runner.rack_handler, get_rackup_or_rack_handler.get('puma')
end
end
end
describe 'with a launch path specified as a proc' do
it 'evaluates the proc in the context of the runner' do
Resque::WebRunner.any_instance.expects(:system).once.with {|s| s =~ /\?search\=blah$/ }
web_runner("--debug", "blah", launch_path: Proc.new {|r| "?search=#{r.args.first}" })
assert @runner.options[:launch_path].is_a?(Proc)
end
end
describe 'with a launch path specified as string' do
it 'launches to the specific path' do
Resque::WebRunner.any_instance.expects(:system).once.with {|s| s =~ /\?search\=blah$/ }
web_runner("--debug", "blah", launch_path: "?search=blah")
assert_equal @runner.options[:launch_path], "?search=blah"
end
end
describe 'without environment' do
before do
@home = ENV.delete('HOME')
@app_dir = './test/tmp'
end
after { ENV['HOME'] = @home }
it 'should be ok with --app-dir' do
web_runner(skip_launch: true, app_dir: @app_dir)
assert_equal @runner.app_dir, @app_dir
end
it 'should raise an exception without --app-dir' do
success = false
begin
Resque::WebRunner.new(skip_launch: true)
rescue ArgumentError
success = true
end
assert success, "ArgumentError not raised."
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/stat_test.rb | test/stat_test.rb | require 'test_helper'
describe "Resque::Stat" do
class DummyStatStore
def initialize
@stat = Hash.new(0)
end
def stat(stat)
@stat[stat]
end
def increment_stat(stat, by = 1, redis: nil)
@stat[stat] += by
end
def decrement_stat(stat, by)
@stat[stat] -= by
end
def clear_stat(stat, redis: nil)
@stat[stat] = 0
end
end
before do
@original_data_store = Resque::Stat.data_store
@dummy_data_store = DummyStatStore.new
Resque::Stat.data_store = @dummy_data_store
end
after do
Resque::Stat.data_store = @original_data_store
end
it '#redis show deprecation warning' do
assert_output(nil, /\[Resque\] \[Deprecation\]/ ) do
assert_equal @dummy_data_store, Resque::Stat.redis
end
end
it '#redis returns data_store' do
assert_equal @dummy_data_store, Resque::Stat.data_store
end
it "#get" do
assert_equal 0, Resque::Stat.get('hello')
end
it "#[]" do
assert_equal 0, Resque::Stat['hello']
end
it "#incr" do
assert_equal 2, Resque::Stat.incr('hello', 2)
assert_equal 2, Resque::Stat['hello']
end
it "#<<" do
assert_equal 1, Resque::Stat << 'hello'
assert_equal 1, Resque::Stat['hello']
end
it "#decr" do
assert_equal 2, Resque::Stat.incr('hello', 2)
assert_equal 2, Resque::Stat['hello']
assert_equal 0, Resque::Stat.decr('hello', 2)
assert_equal 0, Resque::Stat['hello']
end
it "#>>" do
assert_equal 2, Resque::Stat.incr('hello', 2)
assert_equal 2, Resque::Stat['hello']
assert_equal 1, Resque::Stat >> 'hello'
assert_equal 1, Resque::Stat['hello']
end
it '#clear' do
assert_equal 2, Resque::Stat.incr('hello', 2)
assert_equal 2, Resque::Stat['hello']
Resque::Stat.clear('hello')
assert_equal 0, Resque::Stat['hello']
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/job_plugins_test.rb | test/job_plugins_test.rb | require 'test_helper'
describe "Multiple plugins with multiple hooks" do
include PerformJob
module Plugin1
def before_perform_record_history1(history)
history << :before1
end
def after_perform_record_history1(history)
history << :after1
end
end
module Plugin2
def before_perform_record_history2(history)
history << :before2
end
def after_perform_record_history2(history)
history << :after2
end
end
class ::ManyBeforesJob
extend Plugin1
extend Plugin2
def self.perform(history)
history << :perform
end
end
it "hooks of each type are executed in alphabetical order" do
result = perform_job(ManyBeforesJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:before1, :before2, :perform, :after1, :after2], history
end
end
describe "Resque::Plugin ordering before_perform" do
include PerformJob
module BeforePerformPlugin
def before_perform1(history)
history << :before_perform1
end
end
class ::JobPluginsTestBeforePerformJob
extend BeforePerformPlugin
def self.perform(history)
history << :perform
end
def self.before_perform(history)
history << :before_perform
end
end
it "before_perform hooks are executed in order" do
result = perform_job(JobPluginsTestBeforePerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:before_perform, :before_perform1, :perform], history
end
end
describe "Resque::Plugin ordering after_perform" do
include PerformJob
module AfterPerformPlugin
def after_perform_record_history(history)
history << :after_perform1
end
end
class ::JobPluginsTestAfterPerformJob
extend AfterPerformPlugin
def self.perform(history)
history << :perform
end
def self.after_perform(history)
history << :after_perform
end
end
it "after_perform hooks are executed in order" do
result = perform_job(JobPluginsTestAfterPerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:perform, :after_perform, :after_perform1], history
end
end
describe "Resque::Plugin ordering around_perform" do
include PerformJob
module AroundPerformPlugin1
def around_perform1(history)
history << :around_perform_plugin1
yield
end
end
class ::AroundPerformJustPerformsJob
extend AroundPerformPlugin1
def self.perform(history)
history << :perform
end
end
it "around_perform hooks are executed before the job" do
result = perform_job(AroundPerformJustPerformsJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:around_perform_plugin1, :perform], history
end
class ::JobPluginsTestAroundPerformJob
extend AroundPerformPlugin1
def self.perform(history)
history << :perform
end
def self.around_perform(history)
history << :around_perform
yield
end
end
it "around_perform hooks are executed in order" do
result = perform_job(JobPluginsTestAroundPerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:around_perform, :around_perform_plugin1, :perform], history
end
module AroundPerformPlugin2
def around_perform2(history)
history << :around_perform_plugin2
yield
end
end
class ::AroundPerformJob2
extend AroundPerformPlugin1
extend AroundPerformPlugin2
def self.perform(history)
history << :perform
end
def self.around_perform(history)
history << :around_perform
yield
end
end
it "many around_perform are executed in order" do
result = perform_job(AroundPerformJob2, history=[])
assert_equal true, result, "perform returned true"
assert_equal [:around_perform, :around_perform_plugin1, :around_perform_plugin2, :perform], history
end
module AroundPerformDoesNotYield
def around_perform0(history)
history << :around_perform0
end
end
class ::AroundPerformJob3
extend AroundPerformPlugin1
extend AroundPerformPlugin2
extend AroundPerformDoesNotYield
def self.perform(history)
history << :perform
end
def self.around_perform(history)
history << :around_perform
yield
end
end
it "the job is aborted if an around_perform hook does not yield" do
result = perform_job(AroundPerformJob3, history=[])
assert_equal false, result, "perform returned false"
assert_equal [:around_perform, :around_perform0], history
end
module AroundPerformGetsJobResult
@@result = nil
def last_job_result
@@result
end
def around_perform_gets_job_result(*args)
@@result = yield
end
end
class ::AroundPerformJobWithReturnValue < GoodJob
extend AroundPerformGetsJobResult
end
it "the job is not aborted if an around_perform hook does yield" do
result = perform_job(AroundPerformJobWithReturnValue, 'Bob')
assert_equal true, result, "perform returned true"
assert_equal 'Good job, Bob', AroundPerformJobWithReturnValue.last_job_result
end
end
describe "Resque::Plugin ordering on_failure" do
include PerformJob
module OnFailurePlugin
def on_failure1(exception, history)
history << "#{exception.message} plugin"
end
end
class ::FailureJob
extend OnFailurePlugin
def self.perform(history)
history << :perform
raise StandardError, "oh no"
end
def self.on_failure(exception, history)
history << exception.message
end
end
it "on_failure hooks are executed in order" do
history = []
assert_raises StandardError do
perform_job(FailureJob, history)
end
assert_equal [:perform, "oh no", "oh no plugin"], history
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/worker_test.rb | test/worker_test.rb | require 'test_helper'
require 'tmpdir'
describe "Resque::Worker" do
class DummyLogger
def initialize
@rd, @wr = IO.pipe
end
def info(message); @wr << message << "\0"; end
alias_method :debug, :info
alias_method :warn, :info
alias_method :error, :info
alias_method :fatal, :info
def messages
@wr.close
@rd.read.split("\0")
end
end
before do
@worker = Resque::Worker.new(:jobs)
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
end
it 'worker is paused' do
Resque.redis.set('pause-all-workers', 'true')
assert_equal true, @worker.paused?
Resque.redis.set('pause-all-workers', 'TRUE')
assert_equal true, @worker.paused?
Resque.redis.set('pause-all-workers', 'True')
assert_equal true, @worker.paused?
end
it 'worker is not paused' do
assert_equal false, @worker.paused?
Resque.redis.set('pause-all-workers', 'false')
assert_equal false, @worker.paused?
Resque.redis.del('pause-all-workers')
assert_equal false, @worker.paused?
end
it "can fail jobs" do
Resque::Job.create(:jobs, BadJob)
@worker.work(0)
assert_equal 1, Resque::Failure.count
end
it "failed jobs report exception and message" do
Resque::Job.create(:jobs, BadJobWithSyntaxError)
@worker.work(0)
assert_equal('SyntaxError', Resque::Failure.all['exception'])
assert_equal('Extra Bad job!', Resque::Failure.all['error'])
end
it "does not allow exceptions from failure backend to escape" do
job = Resque::Job.new(:jobs, {})
with_failure_backend BadFailureBackend do
@worker.perform job
end
end
it "does not raise exception for completed jobs" do
without_forking do
@worker.work(0)
end
assert_equal 0, Resque::Failure.count
end
it "writes to ENV['PIDFILE'] when supplied and #prepare is called" do
with_pidfile do
tmpfile = Tempfile.new("test_pidfile")
File.expects(:open).with(ENV["PIDFILE"], anything).returns tmpfile
@worker.prepare
end
end
it "daemonizes when ENV['BACKGROUND'] is supplied and #prepare is called" do
Process.expects(:daemon)
with_background do
@worker.prepare
end
end
it "executes at_exit hooks when configured with run_at_exit_hooks" do
tmpfile = File.join(Dir.tmpdir, "resque_at_exit_test_file")
FileUtils.rm_f tmpfile
if worker_pid = Kernel.fork
Process.waitpid(worker_pid)
assert File.exist?(tmpfile), "The file '#{tmpfile}' does not exist"
assert_equal "at_exit", File.open(tmpfile).read.strip
else
# ensure we actually fork
Resque.redis.disconnect!
Resque::Job.create(:at_exit_jobs, AtExitJob, tmpfile)
worker = Resque::Worker.new(:at_exit_jobs)
worker.run_at_exit_hooks = true
suppress_warnings do
worker.work(0)
end
exit
end
end
class ::RaiseExceptionOnFailure
def self.on_failure_throw_exception(exception,*args)
raise "The worker threw an exception"
end
def self.perform
""
end
end
it "should not treat SystemExit as an exception in the child with run_at_exit_hooks == true" do
if worker_pid = Kernel.fork
Process.waitpid(worker_pid)
else
# ensure we actually fork
Resque.redis.disconnect!
Resque::Job.create(:not_failing_job, RaiseExceptionOnFailure)
worker = Resque::Worker.new(:not_failing_job)
worker.run_at_exit_hooks = true
suppress_warnings do
worker.work(0)
end
exit
end
end
it "does not execute at_exit hooks by default" do
tmpfile = File.join(Dir.tmpdir, "resque_at_exit_test_file")
FileUtils.rm_f tmpfile
if worker_pid = Kernel.fork
Process.waitpid(worker_pid)
assert !File.exist?(tmpfile), "The file '#{tmpfile}' exists, at_exit hooks were run"
else
# ensure we actually fork
Resque.redis.disconnect!
Resque::Job.create(:at_exit_jobs, AtExitJob, tmpfile)
worker = Resque::Worker.new(:at_exit_jobs)
suppress_warnings do
worker.work(0)
end
exit
end
end
it "does report failure for jobs with invalid payload" do
job = Resque::Job.new(:jobs, { 'class' => 'NotAValidJobClass', 'args' => '' })
@worker.perform job
assert_equal 1, Resque::Failure.count, 'failure not reported'
end
it "register 'run_at' time on UTC timezone in ISO8601 format" do
job = Resque::Job.new(:jobs, {'class' => 'GoodJob', 'args' => "blah"})
now = Time.now.utc.iso8601
@worker.working_on(job)
assert_equal now, @worker.processing['run_at']
end
it "fails uncompleted jobs with DirtyExit by default on exit" do
job = Resque::Job.new(:jobs, {'class' => 'GoodJob', 'args' => "blah"})
@worker.working_on(job)
@worker.unregister_worker
assert_equal 1, Resque::Failure.count
assert_equal('Resque::DirtyExit', Resque::Failure.all['exception'])
assert_equal('Job still being processed', Resque::Failure.all['error'])
end
it "fails uncompleted jobs with worker exception on exit" do
job = Resque::Job.new(:jobs, {'class' => 'GoodJob', 'args' => "blah"})
@worker.working_on(job)
@worker.unregister_worker(StandardError.new)
assert_equal 1, Resque::Failure.count
assert_equal('StandardError', Resque::Failure.all['exception'])
end
it "does not mask exception when timeout getting job metadata" do
job = Resque::Job.new(:jobs, {'class' => 'GoodJob', 'args' => "blah"})
@worker.working_on(job)
Resque.data_store.redis.stubs(:get).raises(Redis::CannotConnectError)
error_message = "Something bad happened"
exception_caught = assert_raises Redis::CannotConnectError do
@worker.unregister_worker(raised_exception(StandardError,error_message))
end
assert_match(/StandardError/, exception_caught.message)
assert_match(/#{error_message}/, exception_caught.message)
assert_match(/Redis::CannotConnectError/, exception_caught.message)
end
def raised_exception(klass,message)
raise klass,message
rescue Exception => ex
ex
end
class ::SimpleJobWithFailureHandling
def self.on_failure_record_failure(exception, *job_args)
@@exception = exception
end
def self.exception
@@exception
end
end
it "fails uncompleted jobs on exit, and calls failure hook" do
job = Resque::Job.new(:jobs, {'class' => 'SimpleJobWithFailureHandling', 'args' => ""})
@worker.working_on(job)
@worker.unregister_worker
assert_equal 1, Resque::Failure.count
assert_kind_of Resque::DirtyExit, SimpleJobWithFailureHandling.exception
end
it "fails uncompleted jobs on exit and unregisters without erroring out and logs helpful message if error occurs during a failure hook" do
Resque.logger = DummyLogger.new
begin
job = Resque::Job.new(:jobs, {'class' => 'BadJobWithOnFailureHookFail', 'args' => []})
@worker.working_on(job)
@worker.unregister_worker
messages = Resque.logger.messages
ensure
reset_logger
end
assert_equal 1, Resque::Failure.count
error_message = messages.first
assert_match('Additional error (RuntimeError: This job is just so bad!)', error_message)
assert_match('occurred in running failure hooks', error_message)
assert_match('for job (Job{jobs} | BadJobWithOnFailureHookFail | [])', error_message)
assert_match('Original error that caused job failure was RuntimeError: Resque::DirtyExit', error_message)
end
class ::SimpleFailingJob
@@exception_count = 0
def self.on_failure_record_failure(exception, *job_args)
@@exception_count += 1
end
def self.exception_count
@@exception_count
end
def self.perform
raise Exception.new
end
end
it "only calls failure hook once on exception" do
job = Resque::Job.new(:jobs, {'class' => 'SimpleFailingJob', 'args' => ""})
@worker.perform(job)
assert_equal 1, Resque::Failure.count
assert_equal 1, SimpleFailingJob.exception_count
end
it "can peek at failed jobs" do
10.times { Resque::Job.create(:jobs, BadJob) }
@worker.work(0)
assert_equal 10, Resque::Failure.count
assert_equal 10, Resque::Failure.all(0, 20).size
end
it "can clear failed jobs" do
Resque::Job.create(:jobs, BadJob)
@worker.work(0)
assert_equal 1, Resque::Failure.count
Resque::Failure.clear
assert_equal 0, Resque::Failure.count
end
it "catches exceptional jobs" do
Resque::Job.create(:jobs, BadJob)
Resque::Job.create(:jobs, BadJob)
@worker.process
@worker.process
@worker.process
assert_equal 2, Resque::Failure.count
end
it "supports setting the procline to have arbitrary prefixes and suffixes" do
prefix = 'WORKER-TEST-PREFIX/'
suffix = 'worker-test-suffix'
ver = Resque::VERSION
old_prefix = ENV['RESQUE_PROCLINE_PREFIX']
ENV.delete('RESQUE_PROCLINE_PREFIX')
old_procline = $0
@worker.procline(suffix)
assert_equal $0, "resque-#{ver}: #{suffix}"
ENV['RESQUE_PROCLINE_PREFIX'] = prefix
@worker.procline(suffix)
assert_equal $0, "#{prefix}resque-#{ver}: #{suffix}"
$0 = old_procline
if old_prefix.nil?
ENV.delete('RESQUE_PROCLINE_PREFIX')
else
ENV['RESQUE_PROCLINE_PREFIX'] = old_prefix
end
end
it "strips whitespace from queue names" do
queues = "critical, high, low".split(',')
worker = Resque::Worker.new(*queues)
assert_equal %w( critical high low ), worker.queues
end
it "can work on multiple queues" do
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:critical, GoodJob)
worker = Resque::Worker.new(:critical, :high)
worker.process
assert_equal 1, Resque.size(:high)
assert_equal 0, Resque.size(:critical)
worker.process
assert_equal 0, Resque.size(:high)
end
it "can work off one job" do
Resque::Job.create(:jobs, GoodJob)
assert_equal 2, Resque.size(:jobs)
assert_equal true, @worker.work_one_job
assert_equal 1, Resque.size(:jobs)
job = Resque::Job.new(:jobs, {'class' => 'GoodJob'})
assert_equal 1, Resque.size(:jobs)
assert_equal true, @worker.work_one_job(job)
assert_equal 1, Resque.size(:jobs)
@worker.pause_processing
@worker.work_one_job
assert_equal 1, Resque.size(:jobs)
@worker.unpause_processing
assert_equal true, @worker.work_one_job
assert_equal 0, Resque.size(:jobs)
assert_equal false, @worker.work_one_job
end
it "the queues method avoids unnecessary calls to retrieve queue names" do
worker = Resque::Worker.new(:critical, :high, "num*")
actual_queues = ["critical", "high", "num1", "num2"]
Resque.data_store.expects(:queue_names).once.returns(actual_queues)
assert_equal actual_queues, worker.queues
end
it "can work on all queues" do
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:blahblah, GoodJob)
@worker = Resque::Worker.new("*")
@worker.work(0)
assert_equal 0, Resque.size(:high)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:blahblah)
end
it "can work with wildcard at the end of the list" do
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:blahblah, GoodJob)
Resque::Job.create(:beer, GoodJob)
@worker = Resque::Worker.new(:critical, :high, "*")
@worker.work(0)
assert_equal 0, Resque.size(:high)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:blahblah)
assert_equal 0, Resque.size(:beer)
end
it "can work with wildcard at the middle of the list" do
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:blahblah, GoodJob)
Resque::Job.create(:beer, GoodJob)
@worker = Resque::Worker.new(:critical, "*", :high)
@worker.work(0)
assert_equal 0, Resque.size(:high)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:blahblah)
assert_equal 0, Resque.size(:beer)
end
it "processes * queues in alphabetical order" do
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:blahblah, GoodJob)
processed_queues = []
@worker = Resque::Worker.new("*")
without_forking do
@worker.work(0) do |job|
processed_queues << job.queue
end
end
assert_equal %w( jobs high critical blahblah ).sort, processed_queues
end
it "works with globs" do
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:test_one, GoodJob)
Resque::Job.create(:test_two, GoodJob)
@worker = Resque::Worker.new("test_*")
@worker.work(0)
assert_equal 1, Resque.size(:critical)
assert_equal 0, Resque.size(:test_one)
assert_equal 0, Resque.size(:test_two)
end
it "excludes a negated queue" do
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:low, GoodJob)
@worker = Resque::Worker.new(:critical, "!low", "*")
@worker.work(0)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:high)
assert_equal 1, Resque.size(:low)
end
it "excludes multiple negated queues" do
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:foo, GoodJob)
Resque::Job.create(:bar, GoodJob)
@worker = Resque::Worker.new("*", "!foo", "!bar")
@worker.work(0)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:high)
assert_equal 1, Resque.size(:foo)
assert_equal 1, Resque.size(:bar)
end
it "works with negated globs" do
Resque::Job.create(:critical, GoodJob)
Resque::Job.create(:high, GoodJob)
Resque::Job.create(:test_one, GoodJob)
Resque::Job.create(:test_two, GoodJob)
@worker = Resque::Worker.new("*", "!test_*")
@worker.work(0)
assert_equal 0, Resque.size(:critical)
assert_equal 0, Resque.size(:high)
assert_equal 1, Resque.size(:test_one)
assert_equal 1, Resque.size(:test_two)
end
it "has a unique id" do
assert_equal "#{`hostname`.chomp}:#{$$}:jobs", @worker.to_s
end
it "complains if no queues are given" do
assert_raises Resque::NoQueueError do
Resque::Worker.new
end
end
it "fails if a job class has no `perform` method" do
Resque::Job.create(:perform_less, Object)
assert_equal 0, Resque::Failure.count
@worker = Resque::Worker.new(:perform_less)
@worker.work(0)
assert_equal 1, Resque::Failure.count
end
it "inserts itself into the 'workers' list on startup" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert_equal @worker, Resque.workers[0]
end
end
end
it "removes itself from the 'workers' list on shutdown" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert_equal @worker, Resque.workers[0]
end
end
assert_equal [], Resque.workers
end
it "removes worker with stringified id" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
worker_id = Resque.workers[0].to_s
Resque.remove_worker(worker_id)
assert_equal [], Resque.workers
end
end
end
it "records what it is working on" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
task = @worker.job
assert_equal({"args"=>[20, "/tmp"], "class"=>"SomeJob"}, task['payload'])
assert task['run_at']
assert_equal 'jobs', task['queue']
end
end
end
it "clears its status when not working on anything" do
@worker.work(0)
assert_equal Hash.new, @worker.job
end
it "knows when it is working" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert @worker.working?
end
end
end
it "knows when it is idle" do
@worker.work(0)
assert @worker.idle?
end
it "knows who is working" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert_equal [@worker], Resque.working
end
end
end
it "caches the current job iff reloading is disabled" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
first_instance = @worker.job
second_instance = @worker.job
refute_equal first_instance.object_id, second_instance.object_id
first_instance = @worker.job(false)
second_instance = @worker.job(false)
assert_equal first_instance.object_id, second_instance.object_id
end
end
end
it "keeps track of how many jobs it has processed" do
Resque::Job.create(:jobs, BadJob)
Resque::Job.create(:jobs, BadJob)
3.times do
job = @worker.reserve
@worker.process job
end
assert_equal 3, @worker.processed
end
it "keeps track of how many failures it has seen" do
Resque::Job.create(:jobs, BadJob)
Resque::Job.create(:jobs, BadJob)
3.times do
job = @worker.reserve
@worker.process job
end
assert_equal 2, @worker.failed
end
it "stats are erased when the worker goes away" do
@worker.work(0)
assert_equal 0, @worker.processed
assert_equal 0, @worker.failed
end
it "knows when it started" do
time = Time.now
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert Time.parse(@worker.started) - time < 0.1
end
end
end
it "knows whether it exists or not" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
assert Resque::Worker.exists?(@worker)
assert !Resque::Worker.exists?('blah-blah')
end
end
end
it "knows what host it's running on" do
without_forking do
blah_worker = nil
Socket.stub :gethostname, 'blah-blah' do
blah_worker = Resque::Worker.new(:jobs)
blah_worker.register_worker
end
@worker.extend(AssertInWorkBlock).work(0) do
assert Resque::Worker.exists?(blah_worker)
assert_equal Resque::Worker.find(blah_worker).hostname, 'blah-blah'
end
end
end
it "sets $0 while working" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
prefix = ENV['RESQUE_PROCLINE_PREFIX']
ver = Resque::VERSION
assert_equal "#{prefix}resque-#{ver}: Processing jobs since #{Time.now.to_i} [SomeJob]", $0
end
end
end
it "can be found" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
found = Resque::Worker.find(@worker.to_s)
# we ensure that the found ivar @pid is set to the correct value since
# Resque::Worker#pid will use it instead of Process.pid if present
assert_equal @worker.pid, found.instance_variable_get(:@pid)
assert_equal @worker.to_s, found.to_s
assert found.working?
assert_equal @worker.job, found.job
end
end
end
it 'can find others' do
without_forking do
# inject fake worker
other_worker = Resque::Worker.new(:other_jobs)
other_worker.pid = 123456
other_worker.register_worker
begin
@worker.extend(AssertInWorkBlock).work(0) do
found = Resque::Worker.find(other_worker.to_s)
assert_equal other_worker.to_s, found.to_s
assert_equal other_worker.pid, found.pid
assert !found.working?
assert found.job.empty?
end
ensure
other_worker.unregister_worker
end
end
end
it "doesn't find fakes" do
without_forking do
@worker.extend(AssertInWorkBlock).work(0) do
found = Resque::Worker.find('blah-blah')
assert_nil found
end
end
end
it "doesn't write PID file when finding" do
with_pidfile do
File.expects(:open).never
without_forking do
@worker.work(0) do
Resque::Worker.find(@worker.to_s)
end
end
end
end
it "retrieve queues (includes colon) from worker_id" do
worker = Resque::Worker.new("jobs", "foo:bar")
worker.register_worker
found = Resque::Worker.find(worker.to_s)
assert_equal worker.queues, found.queues
end
it "prunes dead workers with heartbeat older than prune interval" do
assert_equal({}, Resque::Worker.all_heartbeats)
now = Time.now
workerA = Resque::Worker.new(:jobs)
workerA.to_s = "bar:3:jobs"
workerA.register_worker
workerA.heartbeat!(now - Resque.prune_interval - 1)
assert_equal 1, Resque.workers.size
assert Resque::Worker.all_heartbeats.key?(workerA.to_s)
workerB = Resque::Worker.new(:jobs)
workerB.to_s = "foo:5:jobs"
workerB.register_worker
workerB.heartbeat!(now)
assert_equal 2, Resque.workers.size
assert Resque::Worker.all_heartbeats.key?(workerB.to_s)
assert_equal [workerA], Resque::Worker.all_workers_with_expired_heartbeats
@worker.prune_dead_workers
assert_equal 1, Resque.workers.size
refute Resque::Worker.all_heartbeats.key?(workerA.to_s)
assert Resque::Worker.all_heartbeats.key?(workerB.to_s)
assert_equal [], Resque::Worker.all_workers_with_expired_heartbeats
end
it "does not prune if another worker has pruned (started pruning) recently" do
now = Time.now
workerA = Resque::Worker.new(:jobs)
workerA.to_s = 'workerA:1:jobs'
workerA.register_worker
workerA.heartbeat!(now - Resque.prune_interval - 1)
assert_equal 1, Resque.workers.size
assert_equal [workerA], Resque::Worker.all_workers_with_expired_heartbeats
workerB = Resque::Worker.new(:jobs)
workerB.to_s = 'workerB:1:jobs'
workerB.register_worker
workerB.heartbeat!(now)
assert_equal 2, Resque.workers.size
workerB.prune_dead_workers
assert_equal [], Resque::Worker.all_workers_with_expired_heartbeats
workerC = Resque::Worker.new(:jobs)
workerC.to_s = "workerC:1:jobs"
workerC.register_worker
workerC.heartbeat!(now - Resque.prune_interval - 1)
assert_equal 2, Resque.workers.size
assert_equal [workerC], Resque::Worker.all_workers_with_expired_heartbeats
workerD = Resque::Worker.new(:jobs)
workerD.to_s = 'workerD:1:jobs'
workerD.register_worker
workerD.heartbeat!(now)
assert_equal 3, Resque.workers.size
# workerC does not get pruned because workerB already pruned recently
workerD.prune_dead_workers
assert_equal [workerC], Resque::Worker.all_workers_with_expired_heartbeats
end
it "does not prune workers that haven't set a heartbeat" do
workerA = Resque::Worker.new(:jobs)
workerA.to_s = "bar:3:jobs"
workerA.register_worker
assert_equal 1, Resque.workers.size
assert_equal({}, Resque::Worker.all_heartbeats)
@worker.prune_dead_workers
assert_equal 1, Resque.workers.size
end
it "prunes workers that haven't been registered but have set a heartbeat" do
assert_equal({}, Resque::Worker.all_heartbeats)
now = Time.now
workerA = Resque::Worker.new(:jobs)
workerA.to_s = "bar:3:jobs"
workerA.heartbeat!(now - Resque.prune_interval - 1)
assert_equal 0, Resque.workers.size
assert Resque::Worker.all_heartbeats.key?(workerA.to_s)
assert_equal [], Resque::Worker.all
@worker.prune_dead_workers
assert_equal 0, Resque.workers.size
assert_equal({}, Resque::Worker.all_heartbeats)
end
it "does return a valid time when asking for heartbeat" do
workerA = Resque::Worker.new(:jobs)
workerA.register_worker
workerA.heartbeat!
assert_instance_of Time, workerA.heartbeat
workerA.remove_heartbeat
assert_nil workerA.heartbeat
end
it "removes old heartbeats before starting heartbeat thread" do
workerA = Resque::Worker.new(:jobs)
workerA.register_worker
workerA.expects(:remove_heartbeat).once
workerA.start_heartbeat
end
it "cleans up heartbeat after unregistering" do
workerA = Resque::Worker.new(:jobs)
workerA.register_worker
workerA.start_heartbeat
Timeout.timeout(5) do
sleep 0.1 while Resque::Worker.all_heartbeats.empty?
assert Resque::Worker.all_heartbeats.key?(workerA.to_s)
assert_instance_of Time, workerA.heartbeat
workerA.unregister_worker
sleep 0.1 until Resque::Worker.all_heartbeats.empty?
end
assert_nil workerA.heartbeat
end
it "does not generate heartbeats that depend on the worker clock, but only on the server clock" do
server_time_before = Resque.data_store.server_time
fake_time = Time.parse("2000-01-01")
with_fake_time(fake_time) do
worker_time = Time.now
workerA = Resque::Worker.new(:jobs)
workerA.register_worker
workerA.heartbeat!
heartbeat_time = workerA.heartbeat
refute_equal heartbeat_time, worker_time
server_time_after = Resque.data_store.server_time
assert server_time_before <= heartbeat_time
assert heartbeat_time <= server_time_after
end
end
it "correctly reports a job that the pruned worker was processing" do
workerA = Resque::Worker.new(:jobs)
workerA.to_s = "jobs01.company.com:3:jobs"
workerA.register_worker
job = Resque::Job.new(:jobs, {'class' => 'GoodJob', 'args' => "blah"})
workerA.working_on(job)
workerA.heartbeat!(Time.now - Resque.prune_interval - 1)
@worker.prune_dead_workers
assert_equal 1, Resque::Failure.count
failure = Resque::Failure.all(0)
assert_equal "Resque::PruneDeadWorkerDirtyExit", failure["exception"]
assert_equal "Worker jobs01.company.com:3:jobs did not gracefully exit while processing GoodJob", failure["error"]
end
# This was added because PruneDeadWorkerDirtyExit does not have a backtrace,
# and the error handling code did not account for that.
it "correctly reports errors that occur while pruning workers" do
workerA = Resque::Worker.new(:jobs)
workerA.to_s = "bar:3:jobs"
workerA.register_worker
workerA.heartbeat!(Time.now - Resque.prune_interval - 1)
# the specific error isn't important, could be something else
Resque.data_store.redis.stubs(:get).raises(Redis::CannotConnectError)
exception_caught = assert_raises Redis::CannotConnectError do
@worker.prune_dead_workers
end
assert_match(/PruneDeadWorkerDirtyExit/, exception_caught.message)
assert_match(/bar:3:jobs/, exception_caught.message)
assert_match(/Redis::CannotConnectError/, exception_caught.message)
end
it "cleans up dead worker info on start (crash recovery)" do
# first we fake out several dead workers
# 1: matches queue and hostname; gets pruned.
workerA = Resque::Worker.new(:jobs)
workerA.instance_variable_set(:@to_s, "#{`hostname`.chomp}:1:jobs")
workerA.register_worker
workerA.heartbeat!
# 2. matches queue but not hostname; no prune.
workerB = Resque::Worker.new(:jobs)
workerB.instance_variable_set(:@to_s, "#{`hostname`.chomp}-foo:2:jobs")
workerB.register_worker
workerB.heartbeat!
# 3. matches hostname but not queue; no prune.
workerB = Resque::Worker.new(:high)
workerB.instance_variable_set(:@to_s, "#{`hostname`.chomp}:3:high")
workerB.register_worker
workerB.heartbeat!
# 4. matches neither hostname nor queue; no prune.
workerB = Resque::Worker.new(:high)
workerB.instance_variable_set(:@to_s, "#{`hostname`.chomp}-foo:4:high")
workerB.register_worker
workerB.heartbeat!
assert_equal 4, Resque.workers.size
# then we prune them
@worker.work(0)
worker_strings = Resque::Worker.all.map(&:to_s)
assert_equal 3, Resque.workers.size
# pruned
assert !worker_strings.include?("#{`hostname`.chomp}:1:jobs")
# not pruned
assert worker_strings.include?("#{`hostname`.chomp}-foo:2:jobs")
assert worker_strings.include?("#{`hostname`.chomp}:3:high")
assert worker_strings.include?("#{`hostname`.chomp}-foo:4:high")
end
it "worker_pids returns pids" do
@worker.work(0)
known_workers = @worker.worker_pids
assert !known_workers.empty?
end
it "Processed jobs count" do
@worker.work(0)
assert_equal 1, Resque.info[:processed]
end
it "Will call a before_first_fork hook only once" do
$BEFORE_FORK_CALLED = 0
Resque.before_first_fork = Proc.new { $BEFORE_FORK_CALLED += 1 }
workerA = Resque::Worker.new(:jobs)
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
assert_equal 0, $BEFORE_FORK_CALLED
workerA.work(0)
assert_equal 1, $BEFORE_FORK_CALLED
#Verify it's only run once.
workerA.work(0)
assert_equal 1, $BEFORE_FORK_CALLED
end
it "Will call a before_pause hook before pausing" do
$BEFORE_PAUSE_CALLED = 0
$WORKER_NAME = nil
Resque.before_pause = Proc.new { |w| $BEFORE_PAUSE_CALLED += 1; $WORKER_NAME = w.to_s; }
workerA = Resque::Worker.new(:jobs)
assert_equal 0, $BEFORE_PAUSE_CALLED
workerA.pause_processing
assert_equal 1, $BEFORE_PAUSE_CALLED
assert_equal workerA.to_s, $WORKER_NAME
end
it "Will call a after_pause hook after pausing" do
$AFTER_PAUSE_CALLED = 0
$WORKER_NAME = nil
Resque.after_pause = Proc.new { |w| $AFTER_PAUSE_CALLED += 1; $WORKER_NAME = w.to_s; }
workerA = Resque::Worker.new(:jobs)
assert_equal 0, $AFTER_PAUSE_CALLED
workerA.unpause_processing
assert_equal 1, $AFTER_PAUSE_CALLED
assert_equal workerA.to_s, $WORKER_NAME
end
it "Will call a before_fork hook before forking" do
$BEFORE_FORK_CALLED = false
Resque.before_fork = Proc.new { $BEFORE_FORK_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$BEFORE_FORK_CALLED
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
workerA.work(0)
assert $BEFORE_FORK_CALLED
end
it "Will not call a before_fork hook when the worker cannot fork" do
without_forking do
$BEFORE_FORK_CALLED = false
Resque.before_fork = Proc.new { $BEFORE_FORK_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$BEFORE_FORK_CALLED, "before_fork should not have been called before job runs"
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
workerA.work(0)
assert !$BEFORE_FORK_CALLED, "before_fork should not have been called after job runs"
end
end
it "Will not call a before_fork hook when forking set to false" do
$BEFORE_FORK_CALLED = false
Resque.before_fork = Proc.new { $BEFORE_FORK_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$BEFORE_FORK_CALLED, "before_fork should not have been called before job runs"
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
# This sets ENV['FORK_PER_JOB'] = 'false' and then restores it
without_forking do
workerA.work(0)
end
assert !$BEFORE_FORK_CALLED, "before_fork should not have been called after job runs"
end
describe "Resque::Job queue_empty" do
before { Resque.send(:clear_hooks, :queue_empty) }
it "will call the queue empty hook when the worker becomes idle" do
# There is already a job in the queue from line 24
$QUEUE_EMPTY_CALLED = false
Resque.queue_empty = Proc.new { $QUEUE_EMPTY_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$QUEUE_EMPTY_CALLED
workerA.work(0)
assert $QUEUE_EMPTY_CALLED
end
it "will not call the queue empty hook on start-up when it has no jobs to process" do
Resque.remove_queue(:jobs)
$QUEUE_EMPTY_CALLED = false
Resque.queue_empty = Proc.new { $QUEUE_EMPTY_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$QUEUE_EMPTY_CALLED
workerA.work(0)
assert !$QUEUE_EMPTY_CALLED
end
it "will call the queue empty hook only once at the beginning and end of a series of jobs" do
$QUEUE_EMPTY_CALLED = 0
Resque.queue_empty = Proc.new { $QUEUE_EMPTY_CALLED += 1 }
workerA = Resque::Worker.new(:jobs)
assert_equal(0, $QUEUE_EMPTY_CALLED)
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
workerA.work(0)
assert_equal(1, $QUEUE_EMPTY_CALLED)
end
end
describe "Resque::Job worker_exit" do
before { Resque.send(:clear_hooks, :worker_exit) }
it "will call the worker exit hook when the worker terminates normally" do
$WORKER_EXIT_CALLED = false
Resque.worker_exit = Proc.new { $WORKER_EXIT_CALLED = true }
workerA = Resque::Worker.new(:jobs)
assert !$WORKER_EXIT_CALLED
workerA.work(0)
assert $WORKER_EXIT_CALLED
end
it "will call the worker exit hook when the worker fails to start" do
$WORKER_EXIT_CALLED = false
Resque.worker_exit = Proc.new { $WORKER_EXIT_CALLED = true }
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | true |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque_failure_multi_queue_test.rb | test/resque_failure_multi_queue_test.rb | require 'test_helper'
require 'resque/failure/redis_multi_queue'
describe "Resque::Failure::RedisMultiQueue" do
let(:bad_string) { [39, 52, 127, 86, 93, 95, 39].map { |c| c.chr }.join }
let(:exception) { StandardError.exception(bad_string) }
let(:worker) { Resque::Worker.new(:test) }
let(:queue) { 'queue' }
let(:payload) { { "class" => "Object", "args" => 3 } }
before do
Resque::Failure::RedisMultiQueue.clear
@redis_backend = Resque::Failure::RedisMultiQueue.new(exception, worker, queue, payload)
end
it 'cleans up bad strings before saving the failure, in order to prevent errors on the resque UI' do
# test assumption: the bad string should not be able to round trip though JSON
@redis_backend.save
Resque::Failure::RedisMultiQueue.all # should not raise an error
end
it '.each iterates correctly (does nothing) for no failures' do
assert_equal 0, Resque::Failure::RedisMultiQueue.count
Resque::Failure::RedisMultiQueue.each do |id, item|
raise "Should not get here"
end
end
it '.each iterates thru a single hash if there is a single failure' do
@redis_backend.save
count = Resque::Failure::RedisMultiQueue.count
assert_equal 1, count
num_iterations = 0
queue = Resque::Failure.failure_queue_name('queue')
Resque::Failure::RedisMultiQueue.each(0, count, queue) do |_id, item|
num_iterations += 1
assert_equal Hash, item.class
end
assert_equal count, num_iterations
end
it '.each iterates thru hashes if there is are multiple failures' do
@redis_backend.save
@redis_backend.save
count = Resque::Failure::RedisMultiQueue.count
assert_equal 2, count
num_iterations = 0
queue = Resque::Failure.failure_queue_name('queue')
Resque::Failure::RedisMultiQueue.each(0, count, queue) do |_id, item|
num_iterations += 1
assert_equal Hash, item.class
end
assert_equal count, num_iterations
end
it '.each should limit based on the class_name when class_name is specified' do
num_iterations = 0
class_one = 'Foo'
class_two = 'Bar'
[ class_one,
class_two,
class_one,
class_two,
class_one,
class_two
].each do |class_name|
Resque::Failure::RedisMultiQueue.new(exception, worker, queue, payload.merge({ "class" => class_name })).save
end
# ensure that there are 6 failed jobs in total as configured
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 6, count
Resque::Failure::RedisMultiQueue.each 0, 3, queue, class_one do |_id, item|
num_iterations += 1
# ensure it iterates only jobs with the specified class name (it was not
# which cause we only got 1 job with class=Foo since it iterates all the
# jobs and limit already reached)
assert_equal class_one, item['payload']['class']
end
# ensure only iterates max up to the limit specified
assert_equal 2, num_iterations
end
it '.each should limit normally when class_name is not specified' do
num_iterations = 0
class_one = 'Foo'
class_two = 'Bar'
[ class_one,
class_two,
class_one,
class_two,
class_one,
class_two
].each do |class_name|
Resque::Failure::RedisMultiQueue.new(exception, worker, queue, payload.merge({ "class" => class_name })).save
end
# ensure that there are 6 failed jobs in total as configured
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 6, count
Resque::Failure::RedisMultiQueue.each 0, 5, queue do |id, item|
num_iterations += 1
assert_equal Hash, item.class
end
# ensure only iterates max up to the limit specified
assert_equal 5, num_iterations
end
it '.each should yield the correct indices when the offset is 0 and the order is descending' do
50.times { @redis_backend.save }
queue = Resque::Failure.failure_queue_name('queue')
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 50, count
offset = 0
limit = 20
ids = []
expected_ids = (offset...limit).to_a.reverse
Resque::Failure::RedisMultiQueue.each offset, limit, queue do |id, _item|
ids << id
end
assert_equal expected_ids, ids
end
it '.each should yield the correct indices when the offset is 0 and the order is ascending' do
50.times { @redis_backend.save }
queue = Resque::Failure.failure_queue_name('queue')
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 50, count
offset = 0
limit = 20
ids = []
expected_ids = (offset...limit).to_a
Resque::Failure::RedisMultiQueue.each offset, limit, queue, nil, 'asc' do |id, _item|
ids << id
end
assert_equal expected_ids, ids
end
it '.each should yield the correct indices when the offset isn\'t 0 and the order is descending' do
50.times { @redis_backend.save }
queue = Resque::Failure.failure_queue_name('queue')
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 50, count
offset = 20
limit = 20
ids = []
expected_ids = (offset...offset + limit).to_a.reverse
Resque::Failure::RedisMultiQueue.each offset, limit, queue do |id, _item|
ids << id
end
assert_equal expected_ids, ids
end
it '.each should yield the correct indices when the offset isn\'t 0 and the order is ascending' do
50.times { @redis_backend.save }
queue = Resque::Failure.failure_queue_name('queue')
count = Resque::Failure::RedisMultiQueue.count
queue = Resque::Failure.failure_queue_name('queue')
assert_equal 50, count
offset = 20
limit = 20
ids = []
expected_ids = (offset...offset + limit).to_a
Resque::Failure::RedisMultiQueue.each offset, limit, queue, nil, 'asc' do |id, _item|
ids << id
end
assert_equal expected_ids, ids
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/child_killing_test.rb | test/child_killing_test.rb | require 'test_helper'
require 'tmpdir'
describe "Resque::Worker" do
class LongRunningJob
@queue = :long_running_job
def self.perform( sleep_time, rescue_time=nil )
Resque.redis.disconnect! # get its own connection
Resque.redis.rpush( 'sigterm-test:start', Process.pid )
sleep sleep_time
Resque.redis.rpush( 'sigterm-test:result', 'Finished Normally' )
rescue Resque::TermException => e
Resque.redis.rpush( 'sigterm-test:result', %Q(Caught TermException: #{e.inspect}))
sleep rescue_time
ensure
Resque.redis.rpush( 'sigterm-test:ensure_block_executed', 'exiting.' )
end
end
def start_worker(rescue_time, term_child, term_timeout = 1)
Resque.enqueue( LongRunningJob, 3, rescue_time )
worker_pid = Kernel.fork do
# disconnect since we just forked
Resque.redis.disconnect!
worker = Resque::Worker.new(:long_running_job)
worker.term_timeout = term_timeout
worker.term_child = term_child
suppress_warnings do
worker.work(0)
end
exit!
end
# ensure the worker is started
start_status = Resque.redis.blpop( 'sigterm-test:start', timeout: 5)
refute_nil start_status
child_pid = start_status[1].to_i
assert child_pid > 0, "worker child process not created"
Process.kill('TERM', worker_pid)
Process.waitpid(worker_pid)
result = Resque.redis.lpop('sigterm-test:result')
[worker_pid, child_pid, result]
end
def assert_exception_caught(result)
refute_nil result
assert !result.start_with?('Finished Normally'), 'Job Finished normally. (sleep parameter to LongRunningJob not long enough?)'
assert result.start_with?("Caught TermException"), 'TermException exception not raised in child.'
end
def assert_child_not_running(child_pid)
# ensure that the child pid is no longer running
child_still_running = !(`ps -p #{child_pid.to_s} -o pid=`).empty?
assert !child_still_running
end
if !defined?(RUBY_ENGINE) || RUBY_ENGINE != "jruby"
it "old signal handling just kills off the child" do
_worker_pid, child_pid, result = start_worker(0, false)
assert_nil result
assert_child_not_running child_pid
end
it "SIGTERM and cleanup occurs in allotted time" do
_worker_pid, child_pid, result = start_worker(0, true)
assert_exception_caught result
assert_child_not_running child_pid
# see if post-cleanup occurred. This should happen IFF the rescue_time is less than the term_timeout
post_cleanup_occurred = Resque.redis.lpop( 'sigterm-test:ensure_block_executed' )
assert post_cleanup_occurred, 'post cleanup did not occur. SIGKILL sent too early?'
end
it "SIGTERM and cleanup does not occur in allotted time" do
_worker_pid, child_pid, result = start_worker(5, true, 0.1)
assert_exception_caught result
assert_child_not_running child_pid
# see if post-cleanup occurred. This should happen IFF the rescue_time is less than the term_timeout
post_cleanup_occurred = Resque.redis.lpop( 'sigterm-test:ensure_block_executed' )
assert !post_cleanup_occurred, 'post cleanup occurred. SIGKILL sent too late?'
end
end
it "exits with Resque::TermException when using TERM_CHILD and not forking" do
old_job_per_fork = ENV['FORK_PER_JOB']
begin
ENV['FORK_PER_JOB'] = 'false'
worker_pid, child_pid, _result = start_worker(0, true)
assert_equal worker_pid, child_pid, "child_pid should equal worker_pid, since we are not forking"
assert Resque.redis.lpop( 'sigterm-test:ensure_block_executed' ), 'post cleanup did not occur. SIGKILL sent too early?'
ensure
ENV['FORK_PER_JOB'] = old_job_per_fork
end
end
it "calls the shutdown hook" do
Resque.send(:clear_hooks, :shutdown)
shutdown_file = Tempfile.new("shutdown_hook")
Resque.shutdown do
# Shutdown hook is called inside a signal handler and can't write to redis
File.open(shutdown_file, "w") { |f| f.write "resque:shutdown_hook_called" }
end
worker_pid, child_pid, _result = start_worker(0, true)
shutdown_hook_called = File.read(shutdown_file) == "resque:shutdown_hook_called"
assert shutdown_hook_called, 'Shutdown hook was not called in parent worker'
end
it "calls the shutdown hook when not forking" do
Resque.send(:clear_hooks, :shutdown)
shutdown_file = Tempfile.new("shutdown_hook")
Resque.shutdown do
# Shutdown hook is called inside a signal handler and can't write to redis
File.open(shutdown_file, "w") { |f| f.write "resque:shutdown_hook_called" }
end
old_fork_per_job = ENV['TERM_CHILD']
begin
ENV['FORK_PER_JOB'] = 'false'
worker_pid, child_pid, _result = start_worker(0, true)
shutdown_hook_called = File.read(shutdown_file) == "resque:shutdown_hook_called"
assert shutdown_hook_called, 'Shutdown hook was not called in parent worker'
ensure
ENV['FORK_PER_JOB'] = old_fork_per_job
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/server_helper_test.rb | test/server_helper_test.rb | require 'test_helper'
require 'resque/server_helper'
describe 'Resque::ServerHelper' do
include Resque::ServerHelper
def exists?(key)
if Gem::Version.new(Redis::VERSION) >= Gem::Version.new('4.2.0')
Resque.redis.exists?(key)
else
Resque.redis.exists(key)
end
end
describe 'redis_get_size' do
describe 'when the data type is none' do
it 'returns 0' do
refute exists?('none')
assert_equal 0, redis_get_size('none')
end
end
describe 'when the data type is hash' do
it 'returns the number of fields contained in the hash' do
Resque.redis.hset('hash','f1', 'v1')
Resque.redis.hset('hash','f2', 'v2')
assert_equal 2, redis_get_size('hash')
end
end
describe 'when the data type is list' do
it 'returns the length of the list' do
Resque.redis.rpush('list', 'v1')
Resque.redis.rpush('list', 'v2')
assert_equal 2, redis_get_size('list')
end
end
describe 'when the data type is set' do
it 'returns the number of elements of the set' do
Resque.redis.sadd('set', ['v1', 'v2'])
assert_equal 2, redis_get_size('set')
end
end
describe 'when the data type is string' do
it 'returns the length of the string' do
Resque.redis.set('string', 'test value')
assert_equal 'test value'.length, redis_get_size('string')
end
end
describe 'when the data type is zset' do
it 'returns the number of elements of the zset' do
Resque.redis.zadd('zset', 1, 'v1')
Resque.redis.zadd('zset', 2, 'v2')
assert_equal 2, redis_get_size('zset')
end
end
end
describe 'redis_get_value_as_array' do
describe 'when the data type is none' do
it 'returns an empty array' do
refute exists?('none')
assert_equal [], redis_get_value_as_array('none')
end
end
describe 'when the data type is hash' do
it 'returns an array of 20 elements counting from `start`' do
Resque.redis.hset('hash','f1', 'v1')
Resque.redis.hset('hash','f2', 'v2')
assert_equal [['f1', 'v1'], ['f2', 'v2']], redis_get_value_as_array('hash')
end
end
describe 'when the data type is list' do
it 'returns an array of 20 elements counting from `start`' do
Resque.redis.rpush('list', 'v1')
Resque.redis.rpush('list', 'v2')
assert_equal ['v1', 'v2'], redis_get_value_as_array('list')
end
end
describe 'when the data type is set' do
it 'returns an array of 20 elements counting from `start`' do
Resque.redis.sadd('set', ['v1', 'v2'])
assert_equal ['v1', 'v2'], redis_get_value_as_array('set').sort
end
end
describe 'when the data type is string' do
it 'returns an array of value' do
Resque.redis.set('string', 'test value')
assert_equal ['test value'], redis_get_value_as_array('string')
end
end
describe 'when the data type is zset' do
it 'returns an array of 20 elements counting from `start`' do
Resque.redis.zadd('zset', 1, 'v1')
Resque.redis.zadd('zset', 2, 'v2')
assert_equal ['v1', 'v2'], redis_get_value_as_array('zset')
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/resque_failure_redis_test.rb | test/resque_failure_redis_test.rb | require 'test_helper'
require 'resque/failure/redis'
describe "Resque::Failure::Redis" do
let(:bad_string) { [39, 52, 127, 86, 93, 95, 39].map { |c| c.chr }.join }
let(:exception) { StandardError.exception(bad_string) }
let(:worker) { Resque::Worker.new(:test) }
let(:queue) { "queue" }
let(:payload) { { "class" => "Object", "args" => 3 } }
before do
Resque::Failure::Redis.clear
@redis_backend = Resque::Failure::Redis.new(exception, worker, queue, payload)
end
it 'cleans up bad strings before saving the failure, in order to prevent errors on the resque UI' do
# test assumption: the bad string should not be able to round trip though JSON
@redis_backend.save
Resque::Failure::Redis.all # should not raise an error
end
it '.each iterates correctly (does nothing) for no failures' do
assert_equal 0, Resque::Failure::Redis.count
Resque::Failure::Redis.each do |id, item|
raise "Should not get here"
end
end
it '.each iterates thru a single hash if there is a single failure' do
@redis_backend.save
assert_equal 1, Resque::Failure::Redis.count
num_iterations = 0
Resque::Failure::Redis.each do |id, item|
num_iterations += 1
assert_equal Hash, item.class
end
assert_equal 1, num_iterations
end
it '.each iterates thru hashes if there is are multiple failures' do
@redis_backend.save
@redis_backend.save
num_iterations = 0
assert_equal 2, Resque::Failure::Redis.count
Resque::Failure::Redis.each do |id, item|
num_iterations += 1
assert_equal Hash, item.class
end
assert_equal 2, num_iterations
end
it '.each should limit based on the class_name when class_name is specified' do
num_iterations = 0
class_one = 'Foo'
class_two = 'Bar'
[ class_one,
class_two,
class_one,
class_two,
class_one,
class_two
].each do |class_name|
Resque::Failure::Redis.new(exception, worker, queue, payload.merge({ "class" => class_name })).save
end
# ensure that there are 6 failed jobs in total as configured
assert_equal 6, Resque::Failure::Redis.count
Resque::Failure::Redis.each 0, 2, nil, class_one do |id, item|
num_iterations += 1
# ensure it iterates only jobs with the specified class name (it was not
# which cause we only got 1 job with class=Foo since it iterates all the
# jobs and limit already reached)
assert_equal class_one, item['payload']['class']
end
# ensure only iterates max up to the limit specified
assert_equal 2, num_iterations
end
it '.each should limit normally when class_name is not specified' do
num_iterations = 0
class_one = 'Foo'
class_two = 'Bar'
[ class_one,
class_two,
class_one,
class_two,
class_one,
class_two
].each do |class_name|
Resque::Failure::Redis.new(exception, worker, queue, payload.merge({ "class" => class_name })).save
end
# ensure that there are 6 failed jobs in total as configured
assert_equal 6, Resque::Failure::Redis.count
Resque::Failure::Redis.each 0, 5 do |id, item|
num_iterations += 1
assert_equal Hash, item.class
end
# ensure only iterates max up to the limit specified
assert_equal 5, num_iterations
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/job_hooks_test.rb | test/job_hooks_test.rb | require 'test_helper'
describe "Resque::Job before_perform" do
include PerformJob
class ::BeforePerformJob
def self.before_perform_record_history(history)
history << :before_perform
end
def self.perform(history)
history << :perform
end
end
it "it runs before_perform before perform" do
result = perform_job(BeforePerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal history, [:before_perform, :perform]
end
class ::BeforePerformJobFails
def self.before_perform_fail_job(history)
history << :before_perform
raise StandardError
end
def self.perform(history)
history << :perform
end
end
it "raises an error and does not perform if before_perform fails" do
history = []
assert_raises StandardError do
perform_job(BeforePerformJobFails, history)
end
assert_equal history, [:before_perform], "Only before_perform was run"
end
class ::BeforePerformJobAborts
def self.before_perform_abort(history)
history << :before_perform
raise Resque::Job::DontPerform
end
def self.perform(history)
history << :perform
end
end
it "does not perform if before_perform raises Resque::Job::DontPerform" do
result = perform_job(BeforePerformJobAborts, history=[])
assert_equal false, result, "perform returned false"
assert_equal history, [:before_perform], "Only before_perform was run"
end
end
describe "Resque::Job after_perform" do
include PerformJob
class ::AfterPerformJob
def self.perform(history)
history << :perform
end
def self.after_perform_record_history(history)
history << :after_perform
end
end
it "it runs after_perform after perform" do
result = perform_job(AfterPerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal history, [:perform, :after_perform]
end
class ::AfterPerformJobFails
def self.perform(history)
history << :perform
end
def self.after_perform_fail_job(history)
history << :after_perform
raise StandardError
end
end
it "raises an error but has already performed if after_perform fails" do
history = []
assert_raises StandardError do
perform_job(AfterPerformJobFails, history)
end
assert_equal history, [:perform, :after_perform], "Only after_perform was run"
end
end
describe "Resque::Job around_perform" do
include PerformJob
class ::AroundPerformJob
def self.perform(history)
history << :perform
end
def self.around_perform_record_history(history)
history << :start_around_perform
yield
history << :finish_around_perform
end
end
it "it runs around_perform then yields in order to perform" do
result = perform_job(AroundPerformJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal history, [:start_around_perform, :perform, :finish_around_perform]
end
class ::AroundPerformJobFailsBeforePerforming
def self.perform(history)
history << :perform
end
def self.around_perform_fail(history)
history << :start_around_perform
raise StandardError
yield
history << :finish_around_perform
end
end
it "raises an error and does not perform if around_perform fails before yielding" do
history = []
assert_raises StandardError do
perform_job(AroundPerformJobFailsBeforePerforming, history)
end
assert_equal history, [:start_around_perform], "Only part of around_perform was run"
end
class ::AroundPerformJobFailsWhilePerforming
def self.perform(history)
history << :perform
raise StandardError
end
def self.around_perform_fail_in_yield(history)
history << :start_around_perform
begin
yield
ensure
history << :ensure_around_perform
end
history << :finish_around_perform
end
end
it "raises an error but may handle exceptions if perform fails" do
history = []
assert_raises StandardError do
perform_job(AroundPerformJobFailsWhilePerforming, history)
end
assert_equal history, [:start_around_perform, :perform, :ensure_around_perform], "Only part of around_perform was run"
end
class ::AroundPerformJobDoesNotHaveToYield
def self.perform(history)
history << :perform
end
def self.around_perform_dont_yield(history)
history << :start_around_perform
history << :finish_around_perform
end
end
it "around_perform is not required to yield" do
history = []
result = perform_job(AroundPerformJobDoesNotHaveToYield, history)
assert_equal false, result, "perform returns false"
assert_equal history, [:start_around_perform, :finish_around_perform], "perform was not run"
end
end
describe "Resque::Job on_failure" do
include PerformJob
class ::FailureJobThatDoesNotFail
def self.perform(history)
history << :perform
end
def self.on_failure_record_failure(exception, history)
history << exception.message
end
end
it "it does not call on_failure if no failures occur" do
result = perform_job(FailureJobThatDoesNotFail, history=[])
assert_equal true, result, "perform returned true"
assert_equal history, [:perform]
end
class ::FailureJobThatFails
def self.perform(history)
history << :perform
raise StandardError, "oh no"
end
def self.on_failure_record_failure(exception, history)
history << exception.message
end
end
it "it calls on_failure with the exception and then re-raises the exception" do
history = []
assert_raises StandardError do
perform_job(FailureJobThatFails, history)
end
assert_equal history, [:perform, "oh no"]
end
class ::FailureJobThatFailsBadly
def self.perform(history)
history << :perform
raise SyntaxError, "oh no"
end
def self.on_failure_record_failure(exception, history)
history << exception.message
end
end
it "it calls on_failure even with bad exceptions" do
history = []
assert_raises SyntaxError do
perform_job(FailureJobThatFailsBadly, history)
end
assert_equal history, [:perform, "oh no"]
end
it "throws errors with helpful messages if failure occurs during on_failure hooks" do
err = assert_raises RuntimeError do
perform_job(BadJobWithOnFailureHookFail)
end
assert_match('Additional error (RuntimeError: This job is just so bad!)', err.message)
assert_match('occurred in running failure hooks', err.message)
assert_match('for job (Job{testqueue} | BadJobWithOnFailureHookFail | [])', err.message)
assert_match('Original error that caused job failure was RuntimeError: SyntaxError: Extra Bad job!', err.message)
end
end
describe "Resque::Job after_enqueue" do
include PerformJob
class ::AfterEnqueueJob
@queue = :jobs
def self.after_enqueue_record_history(history)
history << :after_enqueue
end
def self.perform(history)
end
end
it "the after enqueue hook should run" do
history = []
@worker = Resque::Worker.new(:jobs)
Resque.enqueue(AfterEnqueueJob, history)
@worker.work(0)
assert_equal history, [:after_enqueue], "after_enqueue was not run"
end
end
describe "Resque::Job before_enqueue" do
include PerformJob
class ::BeforeEnqueueJob
@queue = :jobs
def self.before_enqueue_record_history(history)
history << :before_enqueue
end
def self.perform(history)
end
end
class ::BeforeEnqueueJobAbort
@queue = :jobs
def self.before_enqueue_abort(history)
false
end
def self.perform(history)
end
end
it "the before enqueue hook should run" do
history = []
@worker = Resque::Worker.new(:jobs)
assert Resque.enqueue(BeforeEnqueueJob, history)
@worker.work(0)
assert_equal history, [:before_enqueue], "before_enqueue was not run"
end
it "a before enqueue hook that returns false should prevent the job from getting queued" do
Resque.remove_queue(:jobs)
history = []
@worker = Resque::Worker.new(:jobs)
assert_nil Resque.enqueue(BeforeEnqueueJobAbort, history)
assert_equal 0, Resque.size(:jobs)
end
end
describe "Resque::Job after_dequeue" do
include PerformJob
class ::AfterDequeueJob
@queue = :jobs
def self.after_dequeue_record_history(history)
history << :after_dequeue
end
def self.perform(history)
end
end
it "the after dequeue hook should run" do
history = []
@worker = Resque::Worker.new(:jobs)
Resque.dequeue(AfterDequeueJob, history)
@worker.work(0)
assert_equal history, [:after_dequeue], "after_dequeue was not run"
end
end
describe "Resque::Job before_dequeue" do
include PerformJob
class ::BeforeDequeueJob
@queue = :jobs
def self.before_dequeue_record_history(history)
history << :before_dequeue
end
def self.perform(history)
end
end
class ::BeforeDequeueJobAbort
@queue = :jobs
def self.before_dequeue_abort(history)
false
end
def self.perform(history)
end
end
it "the before dequeue hook should run" do
history = []
@worker = Resque::Worker.new(:jobs)
Resque.dequeue(BeforeDequeueJob, history)
@worker.work(0)
assert_equal history, [:before_dequeue], "before_dequeue was not run"
end
it "a before dequeue hook that returns false should prevent the job from getting dequeued" do
history = []
assert_nil Resque.dequeue(BeforeDequeueJobAbort, history)
end
end
describe "Resque::Job all hooks" do
include PerformJob
class ::VeryHookyJob
def self.before_perform_record_history(history)
history << :before_perform
end
def self.around_perform_record_history(history)
history << :start_around_perform
yield
history << :finish_around_perform
end
def self.perform(history)
history << :perform
end
def self.after_perform_record_history(history)
history << :after_perform
end
def self.on_failure_record_history(exception, history)
history << exception.message
end
end
it "the complete hook order" do
result = perform_job(VeryHookyJob, history=[])
assert_equal true, result, "perform returned true"
assert_equal history, [
:before_perform,
:start_around_perform,
:perform,
:finish_around_perform,
:after_perform
]
end
class ::VeryHookyJobThatFails
def self.before_perform_record_history(history)
history << :before_perform
end
def self.around_perform_record_history(history)
history << :start_around_perform
yield
history << :finish_around_perform
end
def self.perform(history)
history << :perform
end
def self.after_perform_record_history(history)
history << :after_perform
raise StandardError, "oh no"
end
def self.on_failure_record_history(exception, history)
history << exception.message
end
end
it "the complete hook order with a failure at the last minute" do
history = []
assert_raises StandardError do
perform_job(VeryHookyJobThatFails, history)
end
assert_equal history, [
:before_perform,
:start_around_perform,
:perform,
:finish_around_perform,
:after_perform,
"oh no"
]
end
class ::CallbacksInline
@queue = :callbacks_inline
def self.before_perform_record_history(history, count)
history << :before_perform
count['count'] += 1
end
def self.after_perform_record_history(history, count)
history << :after_perform
count['count'] += 1
end
def self.around_perform_record_history(history, count)
history << :start_around_perform
count['count'] += 1
yield
history << :finish_around_perform
count['count'] += 1
end
def self.perform(history, count)
history << :perform
$history = history
$count = count
end
end
it "it runs callbacks when inline is true" do
begin
Resque.inline = true
# Sending down two parameters that can be passed and updated by reference
result = Resque.enqueue(CallbacksInline, [], {'count' => 0})
assert_equal true, result, "perform returned true"
assert_equal $history, [:before_perform, :start_around_perform, :perform, :finish_around_perform, :after_perform]
assert_equal 4, $count['count']
ensure
Resque.inline = false
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/helper.rb | test/active_job/helper.rb | # frozen_string_literal: true
require "active_job"
require_relative "support/job_buffer"
GlobalID.app = "aj"
@adapter = ENV["AJ_ADAPTER"] ||= "resque"
puts "Using #{@adapter}"
if ENV["AJ_INTEGRATION_TESTS"]
require "support/integration/helper"
else
ActiveJob::Base.logger = Logger.new(nil)
require "active_job/adapters/#{@adapter}"
end
require "active_support/testing/autorun"
def adapter_is?(*adapter_class_symbols)
adapter_class_symbols.map(&:to_s).include? ActiveJob::Base.queue_adapter_name
end
#require_relative "../../tools/test_common"
ActiveJob::Base.include(ActiveJob::EnqueueAfterTransactionCommit)
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/jobs/hello_job.rb | test/active_job/jobs/hello_job.rb | # frozen_string_literal: true
require_relative "../support/job_buffer"
class HelloJob < ActiveJob::Base
def perform(greeter = "David")
JobBuffer.add("#{greeter} says hello")
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/job_buffer.rb | test/active_job/support/job_buffer.rb | # frozen_string_literal: true
module JobBuffer
class << self
def clear
values.clear
end
def add(value)
values << value
end
def values
@values ||= []
end
def last_value
values.last
end
end
end
class ActiveSupport::TestCase
teardown do
JobBuffer.clear
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/integration/dummy_app_template.rb | test/active_job/support/integration/dummy_app_template.rb | # frozen_string_literal: true
if ENV["AJ_ADAPTER"] == "delayed_job"
generate "delayed_job:active_record", "--quiet"
end
initializer "activejob.rb", <<-CODE
require "#{File.expand_path("jobs_manager.rb", __dir__)}"
JobsManager.current_manager.setup
CODE
initializer "i18n.rb", <<-CODE
I18n.available_locales = [:en, :de]
CODE
file "app/jobs/test_job.rb", <<-CODE
class TestJob < ActiveJob::Base
queue_as :integration_tests
def perform(x)
File.open(Rails.root.join("tmp/\#{x}.new"), "wb+") do |f|
f.write Marshal.dump({
"locale" => I18n.locale.to_s || "en",
"timezone" => Time.zone&.name || "UTC",
"executed_at" => Time.now.to_r
})
end
File.rename(Rails.root.join("tmp/\#{x}.new"), Rails.root.join("tmp/\#{x}"))
end
end
CODE
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/integration/jobs_manager.rb | test/active_job/support/integration/jobs_manager.rb | # frozen_string_literal: true
class JobsManager
@@managers = {}
attr :adapter_name
def self.current_manager
@@managers[ENV["AJ_ADAPTER"]] ||= new(ENV["AJ_ADAPTER"])
end
def initialize(adapter_name)
@adapter_name = adapter_name
require_relative "adapters/#{adapter_name}"
extend "#{adapter_name.camelize}JobsManager".constantize
end
def setup
ActiveJob::Base.queue_adapter = nil
end
def clear_jobs
end
def start_workers
end
def stop_workers
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/integration/helper.rb | test/active_job/support/integration/helper.rb | # frozen_string_literal: true
ENV["RAILS_ENV"] = "test"
ActiveJob::Base.queue_name_prefix = nil
require "rails/generators/rails/app/app_generator"
require "tmpdir"
dummy_app_path = Dir.mktmpdir + "/dummy"
dummy_app_template = File.expand_path("dummy_app_template.rb", __dir__)
args = Rails::Generators::ARGVScrubber.new(["new", dummy_app_path, "--skip-asset-pipeline", "skip-gemfile", "--skip-bundle",
"--skip-git", "-d", "sqlite3", "--skip-javascript", "--force", "--quiet",
"--template", dummy_app_template]).prepare!
Rails::Generators::AppGenerator.start args
require "#{dummy_app_path}/config/environment.rb"
ActiveRecord::Migrator.migrations_paths = [ Rails.root.join("db/migrate").to_s ]
ActiveRecord::Tasks::DatabaseTasks.migrate
require "rails/test_help"
Rails.backtrace_cleaner.remove_silencers!
require_relative "test_case_helpers"
ActiveSupport::TestCase.include(TestCaseHelpers)
JobsManager.current_manager.start_workers
Minitest.after_run do
JobsManager.current_manager.stop_workers
JobsManager.current_manager.clear_jobs
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/integration/test_case_helpers.rb | test/active_job/support/integration/test_case_helpers.rb | # frozen_string_literal: true
require "support/integration/jobs_manager"
module TestCaseHelpers
extend ActiveSupport::Concern
included do
self.use_transactional_tests = false
setup do
clear_jobs
@id = "AJ-#{SecureRandom.uuid}"
end
teardown do
clear_jobs
end
end
private
def jobs_manager
JobsManager.current_manager
end
def clear_jobs
jobs_manager.clear_jobs
end
def wait_for_jobs_to_finish_for(seconds = 60)
Timeout.timeout(seconds) do
while !job_executed do
sleep 0.25
end
end
rescue Timeout::Error
end
def job_file(id)
Dummy::Application.root.join("tmp/#{id}")
end
def job_executed(id = @id)
job_file(id).exist?
end
def job_data(id)
Marshal.load(File.binread(job_file(id)))
end
def job_executed_at(id = @id)
job_data(id)["executed_at"]
end
def job_executed_in_locale(id = @id)
job_data(id)["locale"]
end
def job_executed_in_timezone(id = @id)
job_data(id)["timezone"]
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/integration/adapters/resque.rb | test/active_job/support/integration/adapters/resque.rb | # frozen_string_literal: true
module ResqueJobsManager
def setup
ActiveJob::Base.queue_adapter = :resque
Resque.redis = Redis::Namespace.new "active_jobs_int_test", redis: Redis.new(url: ENV["REDIS_URL"] || "redis://127.0.0.1:6379/12")
Resque.logger = Rails.logger
unless can_run?
puts "Cannot run integration tests for Resque. To be able to run integration tests for Resque you need to install and start Redis.\n"
status = ENV["BUILDKITE"] ? false : true
exit status
end
end
def clear_jobs
Resque.queues.each { |queue_name| Resque.redis.del "queue:#{queue_name}" }
Resque.redis.keys("delayed:*").each { |key| Resque.redis.del "#{key}" }
Resque.redis.del "delayed_queue_schedule"
end
def start_workers
@resque_thread = Thread.new do
w = Resque::Worker.new("integration_tests")
w.term_child = true
w.work(0.5)
end
@scheduler_thread = Thread.new do
Resque::Scheduler.configure do |c|
c.poll_sleep_amount = 0.5
c.dynamic = true
c.quiet = true
c.logfile = nil
end
Resque::Scheduler.master_lock.release!
Resque::Scheduler.run
end
end
def stop_workers
@resque_thread.kill
@scheduler_thread.kill
end
def can_run?
Resque.redis.ping == "PONG"
rescue
false
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/support/stubs/strong_parameters.rb | test/active_job/support/stubs/strong_parameters.rb | # frozen_string_literal: true
class Parameters
def initialize(parameters = {})
@parameters = parameters.with_indifferent_access
end
def permitted?
true
end
def to_h
@parameters.to_h
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/integration/queuing_test.rb | test/active_job/integration/queuing_test.rb | # frozen_string_literal: true
require "helper"
require "jobs/hello_job"
require "active_support/core_ext/numeric/time"
class QueuingTest < ActiveSupport::TestCase
test "should run jobs enqueued on a listening queue" do
TestJob.perform_later @id
wait_for_jobs_to_finish_for(5.seconds)
assert_job_executed
end
test "should not run jobs queued on a non-listening queue" do
old_queue = TestJob.queue_name
begin
TestJob.queue_as :some_other_queue
TestJob.perform_later @id
wait_for_jobs_to_finish_for(2.seconds)
assert_job_not_executed
ensure
TestJob.queue_name = old_queue
end
end
test "resque JobWrapper should have instance variable queue" do
job = ::HelloJob.set(wait: 5.seconds).perform_later
hash = Resque.decode(Resque.find_delayed_selection { true }[0])
assert_equal hash["queue"], job.queue_name
end
test "should not run job enqueued in the future" do
TestJob.set(wait: 10.minutes).perform_later @id
wait_for_jobs_to_finish_for(5.seconds)
assert_job_not_executed
rescue NotImplementedError
pass
end
test "should run job enqueued in the future at the specified time" do
TestJob.set(wait: 5.seconds).perform_later @id
wait_for_jobs_to_finish_for(2.seconds)
assert_job_not_executed
wait_for_jobs_to_finish_for(10.seconds)
assert_job_executed
rescue NotImplementedError
pass
end
test "should run job bulk enqueued in the future at the specified time" do
ActiveJob.perform_all_later([TestJob.new(@id).set(wait: 5.seconds)])
wait_for_jobs_to_finish_for(2.seconds)
assert_job_not_executed
wait_for_jobs_to_finish_for(10.seconds)
assert_job_executed
rescue NotImplementedError
pass
end
test "current locale is kept while running perform_later" do
I18n.available_locales = [:en, :de]
I18n.locale = :de
TestJob.perform_later @id
wait_for_jobs_to_finish_for(5.seconds)
assert_job_executed
assert_equal "de", job_executed_in_locale
ensure
I18n.available_locales = [:en]
I18n.locale = :en
end
test "current timezone is kept while running perform_later" do
current_zone = Time.zone
Time.zone = "Hawaii"
TestJob.perform_later @id
wait_for_jobs_to_finish_for(5.seconds)
assert_job_executed
assert_equal "Hawaii", job_executed_in_timezone
ensure
Time.zone = current_zone
end
private
def assert_job_executed(id = @id)
assert job_executed(id), "Job #{id} was not executed"
end
def assert_job_not_executed(id = @id)
assert_not job_executed(id), "Job #{id} was executed"
end
def assert_job_executed_before(first_id, second_id)
assert job_executed_at(first_id) < job_executed_at(second_id), "Job #{first_id} was not executed before Job #{second_id}"
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/cases/adapter_test.rb | test/active_job/cases/adapter_test.rb | # frozen_string_literal: true
require_relative "../helper"
class AdapterTest < ActiveSupport::TestCase
test "should load #{ENV['AJ_ADAPTER']} adapter" do
assert_equal "active_job/queue_adapters/#{ENV['AJ_ADAPTER']}_adapter".classify, ActiveJob::Base.queue_adapter.class.name
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/test/active_job/adapters/resque.rb | test/active_job/adapters/resque.rb | # frozen_string_literal: true
require "active_job/queue_adapters/resque_adapter"
ActiveJob::Base.queue_adapter = :resque
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/simple.rb | examples/simple.rb | # This is a simple Resque job.
class Archive
@queue = :file_serve
def self.perform(repo_id, branch = 'master')
repo = Repository.find(repo_id)
repo.create_archive(branch)
end
end
# This is in our app code
class Repository < Model
# ... stuff ...
def async_create_archive(branch)
Resque.enqueue(Archive, self.id, branch)
end
# ... more stuff ...
end
# Calling this code:
repo = Repository.find(22)
repo.async_create_archive('homebrew')
# Will return immediately and create a Resque job which is later
# processed.
# Essentially, this code is run by the worker when processing:
Archive.perform(22, 'homebrew')
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/async_helper.rb | examples/async_helper.rb | # If you want to just call a method on an object in the background,
# we can easily add that functionality to Resque.
#
# This is similar to DelayedJob's `send_later`.
#
# Keep in mind that, unlike DelayedJob, only simple Ruby objects
# can be persisted.
#
# If it can be represented in JSON, it can be stored in a job.
# Here's our ActiveRecord class
class Repository < ActiveRecord::Base
# This will be called by a worker when a job needs to be processed
def self.perform(id, method, *args)
find(id).send(method, *args)
end
# We can pass this any Repository instance method that we want to
# run later.
def async(method, *args)
Resque.enqueue(Repository, id, method, *args)
end
end
# Now we can call any method and have it execute later:
@repo.async(:update_disk_usage)
# or
@repo.async(:update_network_source_id, 34)
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/resque_config.rb | examples/resque_config.rb | # puts "evaluating code loaded from config_path in context #{inspect}"
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/instance.rb | examples/instance.rb | # DelayedJob wants you to create instances. No problem.
class Archive < Struct.new(:repo_id, :branch)
def self.perform(*args)
new(*args).perform
end
def perform
# do work!
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/demo/app.rb | examples/demo/app.rb | require 'sinatra/base'
require 'resque'
require 'job'
module Demo
class App < Sinatra::Base
get '/' do
info = Resque.info
out = "<html><head><title>Resque Demo</title></head><body>"
out << "<p>"
out << "There are #{info[:pending]} pending and "
out << "#{info[:processed]} processed jobs across #{info[:queues]} queues."
out << "</p>"
out << '<form method="POST">'
out << '<input type="submit" value="Create New Job"/>'
out << ' <a href="/resque/">View Resque</a>'
out << '</form>'
out << "<form action='/failing' method='POST''>"
out << '<input type="submit" value="Create Failing New Job"/>'
out << ' <a href="/resque/">View Resque</a>'
out << '</form>'
out << "</body></html>"
out
end
post '/' do
Resque.enqueue(Job, params)
redirect "/"
end
post '/failing' do
Resque.enqueue(FailingJob, params)
redirect "/"
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/examples/demo/job.rb | examples/demo/job.rb | require 'resque'
module Demo
module Job
@queue = :default
def self.perform(params)
sleep 1
puts "Processed a job!"
end
end
module FailingJob
@queue = :failing
def self.perform(params)
sleep 1
raise 'not processable!'
puts "Processed a job!"
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque.rb | lib/resque.rb | require 'mono_logger'
require 'redis/namespace'
require 'forwardable'
require 'resque/version'
require 'resque/errors'
require 'resque/failure'
require 'resque/failure/base'
require 'resque/helpers'
require 'resque/stat'
require 'resque/logging'
require 'resque/log_formatters/quiet_formatter'
require 'resque/log_formatters/verbose_formatter'
require 'resque/log_formatters/very_verbose_formatter'
require 'resque/job'
require 'resque/worker'
require 'resque/plugin'
require 'resque/data_store'
require 'resque/thread_signal'
require 'resque/vendor/utf8_util'
require 'resque/railtie' if defined?(Rails::Railtie)
module Resque
include Helpers
extend self
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.dump object
else
MultiJson.encode object
end
end
# Given a string, returns a Ruby object.
def decode(object)
return unless object
begin
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.load object
else
MultiJson.decode object
end
rescue ::MultiJson::DecodeError => e
raise Helpers::DecodeException, e.message, e.backtrace
end
end
# Given a word with dashes, returns a camel cased version of it.
#
# classify('job-name') # => 'JobName'
def classify(dashed_word)
dashed_word.split('-').map(&:capitalize).join
end
# Tries to find a constant with the name specified in the argument string:
#
# constantize("Module") # => Module
# constantize("Test::Unit") # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# constantize("C") # => 'outside', same as ::C
# end
#
# NameError is raised when the constant is unknown.
def constantize(camel_cased_word)
camel_cased_word = camel_cased_word.to_s
if camel_cased_word.include?('-')
camel_cased_word = classify(camel_cased_word)
end
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
args = Module.method(:const_get).arity != 1 ? [false] : []
if constant.const_defined?(name, *args)
constant = constant.const_get(name)
else
constant = constant.const_missing(name)
end
end
constant
end
extend ::Forwardable
# Accepts:
# 1. A 'hostname:port' String
# 2. A 'hostname:port:db' String (to select the Redis db)
# 3. A 'hostname:port/namespace' String (to set the Redis namespace)
# 4. A Redis URL String 'redis://host:port'
# 5. An instance of `Redis`, `Redis::Client`, `Redis::DistRedis`,
# or `Redis::Namespace`.
# 6. An Hash of a redis connection {:host => 'localhost', :port => 6379, :db => 0}
def redis=(server)
case server
when String
if server =~ /rediss?\:\/\//
redis = Redis.new(:url => server)
else
server, namespace = server.split('/', 2)
host, port, db = server.split(':')
redis = Redis.new(:host => host, :port => port, :db => db)
end
namespace ||= :resque
@data_store = Resque::DataStore.new(Redis::Namespace.new(namespace, :redis => redis))
when Redis::Namespace
@data_store = Resque::DataStore.new(server)
when Resque::DataStore
@data_store = server
when Hash
@data_store = Resque::DataStore.new(Redis::Namespace.new(:resque, :redis => Redis.new(server)))
else
@data_store = Resque::DataStore.new(Redis::Namespace.new(:resque, :redis => server))
end
end
# Returns the current Redis connection. If none has been created, will
# create a new one.
def redis
return @data_store if @data_store
self.redis = Redis.respond_to?(:connect) ? Redis.connect : "localhost:6379"
self.redis
end
alias :data_store :redis
def redis_id
data_store.identifier
end
# Set the data store for the processed and failed statistics.
#
# By default it uses the same as `Resque.redis`, but different stores can be used.
#
# A custom store needs to obey the following API to work correctly
#
# class NullDataStore
# # Returns the current value for the given stat.
# def stat(stat)
# end
#
# # Increments the stat by the given value.
# def increment_stat(stat, by)
# end
#
# # Decrements the stat by the given value.
# def decrement_stat(stat, by)
# end
#
# # Clear the values for the given stat.
# def clear_stat(stat)
# end
# end
def stat_data_store=(stat_data_store)
Resque::Stat.data_store = stat_data_store
end
# Returns the data store for the statistics module.
def stat_data_store
Resque::Stat.data_store
end
# Set or retrieve the current logger object
attr_accessor :logger
DEFAULT_HEARTBEAT_INTERVAL = 60
DEFAULT_PRUNE_INTERVAL = DEFAULT_HEARTBEAT_INTERVAL * 5
# Defines how often a Resque worker updates the heartbeat key. Must be less
# than the prune interval.
attr_writer :heartbeat_interval
def heartbeat_interval
if defined? @heartbeat_interval
@heartbeat_interval
else
DEFAULT_HEARTBEAT_INTERVAL
end
end
# Defines how often Resque checks for dead workers.
attr_writer :prune_interval
def prune_interval
if defined? @prune_interval
@prune_interval
else
DEFAULT_PRUNE_INTERVAL
end
end
# By default, jobs are pushed to the back of the queue and popped from
# the front, resulting in "first in, first out" (FIFO) execution order.
# Set to true to push jobs to the front of the queue instead, resulting
# in "last in, first out" (LIFO) execution order.
attr_writer :enqueue_front
def enqueue_front
if defined? @enqueue_front
@enqueue_front
else
@enqueue_front = false
end
end
# The `before_first_fork` hook will be run in the **parent** process
# only once, before forking to run the first job. Be careful- any
# changes you make will be permanent for the lifespan of the
# worker.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def before_first_fork(&block)
block ? register_hook(:before_first_fork, block) : hooks(:before_first_fork)
end
# Register a before_first_fork proc.
def before_first_fork=(block)
register_hook(:before_first_fork, block)
end
# The `before_fork` hook will be run in the **parent** process
# before every job, so be careful- any changes you make will be
# permanent for the lifespan of the worker.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def before_fork(&block)
block ? register_hook(:before_fork, block) : hooks(:before_fork)
end
# Register a before_fork proc.
def before_fork=(block)
register_hook(:before_fork, block)
end
# The `after_fork` hook will be run in the child process and is passed
# the current job. Any changes you make, therefore, will only live as
# long as the job currently being processed.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def after_fork(&block)
block ? register_hook(:after_fork, block) : hooks(:after_fork)
end
# Register an after_fork proc.
def after_fork=(block)
register_hook(:after_fork, block)
end
# The `before_pause` hook will be run in the parent process before the
# worker has paused processing (via #pause_processing or SIGUSR2).
def before_pause(&block)
block ? register_hook(:before_pause, block) : hooks(:before_pause)
end
# Register a before_pause proc.
def before_pause=(block)
register_hook(:before_pause, block)
end
# The `after_pause` hook will be run in the parent process after the
# worker has paused (via SIGCONT).
def after_pause(&block)
block ? register_hook(:after_pause, block) : hooks(:after_pause)
end
# Register an after_pause proc.
def after_pause=(block)
register_hook(:after_pause, block)
end
# The `queue_empty` hook will be run in the **parent** process when
# the worker finds no more jobs in the queue and becomes idle.
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def queue_empty(&block)
block ? register_hook(:queue_empty, block) : hooks(:queue_empty)
end
# Register a queue_empty proc.
def queue_empty=(block)
register_hook(:queue_empty, block)
end
# The `worker_exit` hook will be run in the **parent** process
# after the worker has existed (via SIGQUIT, SIGTERM, SIGINT, etc.).
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def worker_exit(&block)
block ? register_hook(:worker_exit, block) : hooks(:worker_exit)
end
# Register a worker_exit proc.
def worker_exit=(block)
register_hook(:worker_exit, block)
end
# The `shutdown` hook will be run in the **child** process
# when the worker has received a signal to stop processing
#
# Call with a block to register a hook.
# Call with no arguments to return all registered hooks.
def shutdown(&block)
block ? register_hook(:shutdown, block) : hooks(:shutdown)
end
# Register a shutdown proc.
def shutdown=(block)
register_hook(:shutdown, block)
end
def to_s
"Resque Client connected to #{redis_id}"
end
attr_accessor :inline
# If 'inline' is true Resque will call #perform method inline
# without queuing it into Redis and without any Resque callbacks.
# The 'inline' is false Resque jobs will be put in queue regularly.
alias :inline? :inline
#
# queue manipulation
#
# Pushes a job onto a queue. Queue name should be a string and the
# item should be any JSON-able Ruby object.
#
# Resque works generally expect the `item` to be a hash with the following
# keys:
#
# class - The String name of the job to run.
# args - An Array of arguments to pass the job. Usually passed
# via `class.to_class.perform(*args)`.
#
# Example
#
# Resque.push('archive', :class => 'Archive', :args => [ 35, 'tar' ])
#
# Returns nothing
def push(queue, item)
data_store.push_to_queue(queue,encode(item))
end
# Pops a job off a queue. Queue name should be a string.
#
# Returns a Ruby object.
def pop(queue)
decode(data_store.pop_from_queue(queue))
end
# Returns an integer representing the size of a queue.
# Queue name should be a string.
def size(queue)
data_store.queue_size(queue)
end
# Returns an array of items currently queued, or the item itself
# if count = 1. Queue name should be a string.
#
# start and count should be integer and can be used for pagination.
# start is the item to begin, count is how many items to return.
#
# To get the 3rd page of a 30 item, paginatied list one would use:
# Resque.peek('my_list', 59, 30)
def peek(queue, start = 0, count = 1)
results = data_store.peek_in_queue(queue,start,count)
if count == 1
decode(results)
else
results.map { |result| decode(result) }
end
end
# Does the dirty work of fetching a range of items from a Redis list
# and converting them into Ruby objects.
def list_range(key, start = 0, count = 1)
results = data_store.list_range(key, start, count)
if count == 1
decode(results)
else
results.map { |result| decode(result) }
end
end
# Returns an array of all known Resque queues as strings.
def queues
data_store.queue_names
end
# Given a queue name, completely deletes the queue.
def remove_queue(queue)
data_store.remove_queue(queue)
end
# Used internally to keep track of which queues we've created.
# Don't call this directly.
def watch_queue(queue)
data_store.watch_queue(queue)
end
#
# job shortcuts
#
# This method can be used to conveniently add a job to a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue(klass, *args)
enqueue_to(queue_from_class(klass), klass, *args)
end
# Just like `enqueue` but allows you to specify the queue you want to
# use. Runs hooks.
#
# `queue` should be the String name of the queue you're targeting.
#
# Returns true if the job was queued, nil if the job was rejected by a
# before_enqueue hook.
#
# This method is considered part of the `stable` API.
def enqueue_to(queue, klass, *args)
# Perform before_enqueue hooks. Don't perform enqueue if any hook returns false
before_hooks = Plugin.before_enqueue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return nil if before_hooks.any? { |result| result == false }
Job.create(queue, klass, *args)
Plugin.after_enqueue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
return true
end
# This method can be used to conveniently remove a job from a queue.
# It assumes the class you're passing it is a real Ruby class (not
# a string or reference) which either:
#
# a) has a @queue ivar set
# b) responds to `queue`
#
# If either of those conditions are met, it will use the value obtained
# from performing one of the above operations to determine the queue.
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If no args are given, this method will dequeue *all* jobs matching
# the provided class. See `Resque::Job.destroy` for more
# information.
#
# Returns the number of jobs destroyed.
#
# Example:
#
# # Removes all jobs of class `UpdateNetworkGraph`
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph)
#
# # Removes all jobs of class `UpdateNetworkGraph` with matching args.
# Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph, 'repo:135325')
#
# This method is considered part of the `stable` API.
def dequeue(klass, *args)
# Perform before_dequeue hooks. Don't perform dequeue if any hook returns false
before_hooks = Plugin.before_dequeue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return if before_hooks.any? { |result| result == false }
destroyed = Job.destroy(queue_from_class(klass), klass, *args)
Plugin.after_dequeue_hooks(klass).each do |hook|
klass.send(hook, *args)
end
destroyed
end
# Given a class, try to extrapolate an appropriate queue based on a
# class instance variable or `queue` method.
def queue_from_class(klass)
(klass.instance_variable_defined?(:@queue) && klass.instance_variable_get(:@queue)) ||
(klass.respond_to?(:queue) and klass.queue)
end
# This method will return a `Resque::Job` object or a non-true value
# depending on whether a job can be obtained. You should pass it the
# precise name of a queue: case matters.
#
# This method is considered part of the `stable` API.
def reserve(queue)
Job.reserve(queue)
end
# Validates if the given klass could be a valid Resque job
#
# If no queue can be inferred this method will raise a `Resque::NoQueueError`
#
# If given klass is nil this method will raise a `Resque::NoClassError`
def validate(klass, queue = nil)
queue ||= queue_from_class(klass)
if !queue
raise NoQueueError.new("Jobs must be placed onto a queue. No queue could be inferred for class #{klass}")
end
if klass.to_s.empty?
raise NoClassError.new("Jobs must be given a class.")
end
end
#
# worker shortcuts
#
# A shortcut to Worker.all
def workers
Worker.all
end
# A shortcut to Worker.working
def working
Worker.working
end
# A shortcut to unregister_worker
# useful for command line tool
def remove_worker(worker_id)
worker = Resque::Worker.find(worker_id)
worker.unregister_worker
end
#
# stats
#
# Returns a hash, similar to redis-rb's #info, of interesting stats.
def info
return {
:pending => queue_sizes.inject(0) { |sum, (_queue_name, queue_size)| sum + queue_size },
:processed => Stat[:processed],
:queues => queues.size,
:workers => workers.size.to_i,
:working => working.size,
:failed => data_store.num_failed,
:servers => [redis_id],
:environment => ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
}
end
# Returns an array of all known Resque keys in Redis. Redis' KEYS operation
# is O(N) for the keyspace, so be careful - this can be slow for big databases.
def keys
data_store.all_resque_keys
end
# Returns a hash, mapping queue names to queue sizes
def queue_sizes
queue_names = queues
sizes = redis.pipelined do |piped|
queue_names.each do |name|
piped.llen("queue:#{name}")
end
end
Hash[queue_names.zip(sizes)]
end
# Returns a hash, mapping queue names to (up to `sample_size`) samples of jobs in that queue
def sample_queues(sample_size = 1000)
queue_names = queues
samples = redis.pipelined do |piped|
queue_names.each do |name|
key = "queue:#{name}"
piped.llen(key)
piped.lrange(key, 0, sample_size - 1)
end
end
hash = {}
queue_names.zip(samples.each_slice(2).to_a) do |queue_name, (queue_size, serialized_samples)|
samples = serialized_samples.map do |serialized_sample|
Job.decode(serialized_sample)
end
hash[queue_name] = {
:size => queue_size,
:samples => samples
}
end
hash
end
private
@hooks = Hash.new { |h, k| h[k] = [] }
# Register a new proc as a hook. If the block is nil this is the
# equivalent of removing all hooks of the given name.
#
# `name` is the hook that the block should be registered with.
def register_hook(name, block)
return clear_hooks(name) if block.nil?
block = Array(block)
@hooks[name].concat(block)
end
# Clear all hooks given a hook name.
def clear_hooks(name)
@hooks[name] = []
end
# Retrieve all hooks of a given name.
def hooks(name)
@hooks[name]
end
end
# Log to STDOUT by default
Resque.logger = MonoLogger.new(STDOUT)
Resque.logger.formatter = Resque::QuietFormatter.new
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/version.rb | lib/resque/version.rb | module Resque
VERSION = '2.7.0'
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/errors.rb | lib/resque/errors.rb | module Resque
# Raised whenever we need a queue but none is provided.
class NoQueueError < RuntimeError; end
# Raised when trying to create a job without a class
class NoClassError < RuntimeError; end
# Raised when a worker was killed while processing a job.
class DirtyExit < RuntimeError
attr_reader :process_status
def initialize(message=nil, process_status=nil)
@process_status = process_status
super message
end
end
class PruneDeadWorkerDirtyExit < DirtyExit
def initialize(hostname, job)
job ||= "<Unknown Job>"
super("Worker #{hostname} did not gracefully exit while processing #{job}")
end
end
# Raised when child process is TERM'd so job can rescue this to do shutdown work.
class TermException < SignalException; end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/logging.rb | lib/resque/logging.rb | module Resque
# Include this module in classes you wish to have logging facilities
module Logging
module_function
# Thunk to the logger's own log method (if configured)
def self.log(severity, message)
Resque.logger.__send__(severity, message) if Resque.logger
end
# Log level aliases
def debug(message); Logging.log :debug, message; end
def info(message); Logging.log :info, message; end
def warn(message); Logging.log :warn, message; end
def error(message); Logging.log :error, message; end
def fatal(message); Logging.log :fatal, message; end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/stat.rb | lib/resque/stat.rb | module Resque
# The stat subsystem. Used to keep track of integer counts.
#
# Get a stat: Stat[name]
# Incr a stat: Stat.incr(name)
# Decr a stat: Stat.decr(name)
# Kill a stat: Stat.clear(name)
module Stat
extend self
def redis
warn '[Resque] [Deprecation] Resque::Stat #redis method is deprecated (please use #data_store)'
data_store
end
def data_store
@data_store ||= Resque.redis
end
def data_store=(data_store)
@data_store = data_store
end
# Returns the int value of a stat, given a string stat name.
def get(stat)
data_store.stat(stat)
end
# Alias of `get`
def [](stat)
get(stat)
end
# For a string stat name, increments the stat by one.
#
# Can optionally accept a second int parameter. The stat is then
# incremented by that amount.
def incr(stat, by = 1, **opts)
data_store.increment_stat(stat, by, **opts)
end
# Increments a stat by one.
def <<(stat)
incr stat
end
# For a string stat name, decrements the stat by one.
#
# Can optionally accept a second int parameter. The stat is then
# decremented by that amount.
def decr(stat, by = 1)
data_store.decrement_stat(stat,by)
end
# Decrements a stat by one.
def >>(stat)
decr stat
end
# Removes a stat from Redis, effectively setting it to 0.
def clear(stat, **opts)
data_store.clear_stat(stat, **opts)
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/plugin.rb | lib/resque/plugin.rb | module Resque
module Plugin
extend self
LintError = Class.new(RuntimeError)
# Ensure that your plugin conforms to good hook naming conventions.
#
# Resque::Plugin.lint(MyResquePlugin)
def lint(plugin)
hooks = before_hooks(plugin) + around_hooks(plugin) + after_hooks(plugin)
hooks.each do |hook|
if hook.to_s.end_with?("perform")
raise LintError, "#{plugin}.#{hook} is not namespaced"
end
end
failure_hooks(plugin).each do |hook|
if hook.to_s.end_with?("failure")
raise LintError, "#{plugin}.#{hook} is not namespaced"
end
end
end
@job_methods = {}
def job_methods(job)
@job_methods[job] ||= job.methods.collect{|m| m.to_s}
end
# Given an object, and a method prefix, returns a list of methods prefixed
# with that name (hook names).
def get_hook_names(job, hook_method_prefix)
methods = (job.respond_to?(:hooks) && job.hooks) || job_methods(job)
methods.select{|m| m.start_with?(hook_method_prefix)}.sort
end
# Given an object, returns a list `before_perform` hook names.
def before_hooks(job)
get_hook_names(job, 'before_perform')
end
# Given an object, returns a list `around_perform` hook names.
def around_hooks(job)
get_hook_names(job, 'around_perform')
end
# Given an object, returns a list `after_perform` hook names.
def after_hooks(job)
get_hook_names(job, 'after_perform')
end
# Given an object, returns a list `on_failure` hook names.
def failure_hooks(job)
get_hook_names(job, 'on_failure')
end
# Given an object, returns a list `after_enqueue` hook names.
def after_enqueue_hooks(job)
get_hook_names(job, 'after_enqueue')
end
# Given an object, returns a list `before_enqueue` hook names.
def before_enqueue_hooks(job)
get_hook_names(job, 'before_enqueue')
end
# Given an object, returns a list `after_dequeue` hook names.
def after_dequeue_hooks(job)
get_hook_names(job, 'after_dequeue')
end
# Given an object, returns a list `before_dequeue` hook names.
def before_dequeue_hooks(job)
get_hook_names(job, 'before_dequeue')
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/helpers.rb | lib/resque/helpers.rb | require 'multi_json'
# OkJson won't work because it doesn't serialize symbols
# in the same way yajl and json do.
if MultiJson.respond_to?(:adapter)
raise "Please install the yajl-ruby or json gem" if MultiJson.adapter.to_s == 'MultiJson::Adapters::OkJson'
elsif MultiJson.respond_to?(:engine)
raise "Please install the yajl-ruby or json gem" if MultiJson.engine.to_s == 'MultiJson::Engines::OkJson'
end
module Resque
# Methods used by various classes in Resque.
module Helpers
class DecodeException < StandardError; end
# Direct access to the Redis instance.
def redis
# No infinite recursions, please.
# Some external libraries depend on Resque::Helpers being mixed into
# Resque, but this method causes recursions. If we have a super method,
# assume it is canonical. (see #1150)
return super if defined?(super)
Resque.redis
end
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
Resque.encode(object)
end
# Given a string, returns a Ruby object.
def decode(object)
Resque.decode(object)
end
# Given a word with dashes, returns a camel cased version of it.
def classify(dashed_word)
Resque.classify(dashed_word)
end
# Tries to find a constant with the name specified in the argument string
def constantize(camel_cased_word)
Resque.constantize(camel_cased_word)
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/railtie.rb | lib/resque/railtie.rb | module Resque
class Railtie < Rails::Railtie
rake_tasks do
require 'resque/tasks'
# redefine ths task to load the rails env
task "resque:setup" => :environment
end
initializer "resque.active_job" do
ActiveSupport.on_load(:active_job) do
require "active_job/queue_adapters/resque_adapter"
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/thread_signal.rb | lib/resque/thread_signal.rb | class Resque::ThreadSignal
def initialize
@mutex = Mutex.new
@signaled = false
@received = ConditionVariable.new
end
def signal
@mutex.synchronize do
@signaled = true
@received.signal
end
end
def wait_for_signal(timeout)
@mutex.synchronize do
unless @signaled
@received.wait(@mutex, timeout)
end
@signaled
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/web_runner.rb | lib/resque/web_runner.rb | require 'open-uri'
require 'logger'
require 'optparse'
require 'fileutils'
require 'rack'
begin
require 'rackup'
rescue LoadError
end
require 'resque/server'
# only used with `bin/resque-web`
# https://github.com/resque/resque/pull/1780
module Resque
WINDOWS = !!(RUBY_PLATFORM =~ /(mingw|bccwin|wince|mswin32)/i)
JRUBY = !!(RbConfig::CONFIG["RUBY_INSTALL_NAME"] =~ /^jruby/i)
class WebRunner
attr_reader :app, :app_name, :filesystem_friendly_app_name,
:rack_handler, :port, :options, :args
PORT = 5678
HOST = WINDOWS ? 'localhost' : '0.0.0.0'
def initialize(*runtime_args)
@options = runtime_args.last.is_a?(Hash) ? runtime_args.pop : {}
self.class.logger.level = options[:debug] ? Logger::DEBUG : Logger::INFO
@app = Resque::Server
@app_name = 'resque-web'
@filesystem_friendly_app_name = @app_name.gsub(/\W+/, "_")
@args = load_options(runtime_args)
@rack_handler = (s = options[:rack_handler]) ? self.class.get_rackup_or_rack_handler.get(s) : setup_rack_handler
case option_parser.command
when :help
puts option_parser
when :kill
kill!
when :status
status
when :version
puts "resque #{Resque::VERSION}"
puts "rack #{Rack::VERSION.join('.')}"
puts "sinatra #{Sinatra::VERSION}" if defined?(Sinatra)
else
before_run
start unless options[:start] == false
end
end
def launch_path
if options[:launch_path].respond_to?(:call)
options[:launch_path].call(self)
else
options[:launch_path]
end
end
def app_dir
if !options[:app_dir] && !ENV['HOME']
raise ArgumentError.new("nor --app-dir neither ENV['HOME'] defined")
end
options[:app_dir] || File.join(ENV['HOME'], filesystem_friendly_app_name)
end
def pid_file
options[:pid_file] || File.join(app_dir, "#{filesystem_friendly_app_name}.pid")
end
def url_file
options[:url_file] || File.join(app_dir, "#{filesystem_friendly_app_name}.url")
end
def log_file
options[:log_file] || File.join(app_dir, "#{filesystem_friendly_app_name}.log")
end
def host
options.fetch(:host) { HOST }
end
def url
"http://#{host}:#{port}"
end
def before_run
if (redis_conf = options[:redis_conf])
logger.info "Using Redis connection '#{redis_conf}'"
Resque.redis = redis_conf
end
if (namespace = options[:redis_namespace])
logger.info "Using Redis namespace '#{namespace}'"
Resque.redis.namespace = namespace
end
if (url_prefix = options[:url_prefix])
logger.info "Using URL Prefix '#{url_prefix}'"
Resque::Server.url_prefix = url_prefix
end
app.set(options.merge web_runner: self)
path = (ENV['RESQUECONFIG'] || args.first)
load_config_file(path.to_s.strip) if path
end
def start(path = launch_path)
logger.info "Running with Windows Settings" if WINDOWS
logger.info "Running with JRuby" if JRUBY
logger.info "Starting '#{app_name}'..."
check_for_running(path)
find_port
write_url
launch!(url, path)
daemonize! unless options[:foreground]
run!
rescue RuntimeError => e
logger.warn "There was an error starting '#{app_name}': #{e}"
exit
end
def find_port
if @port = options[:port]
announce_port_attempted
unless port_open?
logger.warn "Port #{port} is already in use. Please try another. " +
"You can also omit the port flag, and we'll find one for you."
end
else
@port = PORT
announce_port_attempted
until port_open?
@port += 1
announce_port_attempted
end
end
end
def announce_port_attempted
logger.info "trying port #{port}..."
end
def port_open?(check_url = nil)
begin
check_url ||= url
options[:no_proxy] ? uri_open(check_url, :proxy => nil) : uri_open(check_url)
false
rescue Errno::ECONNREFUSED, Errno::EPERM, Errno::ETIMEDOUT
true
end
end
def uri_open(*args)
(RbConfig::CONFIG['ruby_version'] < '2.7') ? open(*args) : URI.open(*args)
end
def write_url
# Make sure app dir is setup
FileUtils.mkdir_p(app_dir)
File.open(url_file, 'w') {|f| f << url }
end
def check_for_running(path = nil)
if File.exist?(pid_file) && File.exist?(url_file)
running_url = File.read(url_file)
if !port_open?(running_url)
logger.warn "'#{app_name}' is already running at #{running_url}"
launch!(running_url, path)
exit!(1)
end
end
end
def run!
logger.info "Running with Rack handler: #{@rack_handler.inspect}"
rack_handler.run app, :Host => host, :Port => port do |server|
kill_commands.each do |command|
trap(command) do
## Use thins' hard #stop! if available, otherwise just #stop
server.respond_to?(:stop!) ? server.stop! : server.stop
logger.info "'#{app_name}' received INT ... stopping"
delete_pid!
end
end
end
end
# Adapted from Rackup
def daemonize!
if JRUBY
# It's not a true daemon but when executed with & works like one
thread = Thread.new {daemon_execute}
thread.join
elsif RUBY_VERSION < "1.9"
logger.debug "Parent Process: #{Process.pid}"
exit!(0) if fork
logger.debug "Child Process: #{Process.pid}"
daemon_execute
else
Process.daemon(true, true)
daemon_execute
end
end
def daemon_execute
File.umask 0000
FileUtils.touch log_file
STDIN.reopen log_file
STDOUT.reopen log_file, "a"
STDERR.reopen log_file, "a"
logger.debug "Child Process: #{Process.pid}"
File.open(pid_file, 'w') {|f| f.write("#{Process.pid}") }
at_exit { delete_pid! }
end
def launch!(specific_url = nil, path = nil)
return if options[:skip_launch]
cmd = WINDOWS ? "start" : "open"
system "#{cmd} #{specific_url || url}#{path}"
end
def kill!
pid = File.read(pid_file)
logger.warn "Sending #{kill_command} to #{pid.to_i}"
Process.kill(kill_command, pid.to_i)
rescue => e
logger.warn "pid not found at #{pid_file} : #{e}"
end
def status
if File.exist?(pid_file)
logger.info "'#{app_name}' running"
logger.info "PID #{File.read(pid_file)}"
logger.info "URL #{File.read(url_file)}" if File.exist?(url_file)
else
logger.info "'#{app_name}' not running!"
end
end
# Loads a config file at config_path and evals it in the context of the @app.
def load_config_file(config_path)
abort "Can not find config file at #{config_path}" if !File.readable?(config_path)
config = File.read(config_path)
# trim off anything after __END__
config.sub!(/^__END__\n.*/, '')
@app.module_eval(config)
end
def self.logger=(logger)
@logger = logger
end
def self.logger
@logger ||= LOGGER if defined?(LOGGER)
if !@logger
@logger = Logger.new(STDOUT)
@logger.formatter = Proc.new {|s, t, n, msg| "[#{t}] #{msg}\n"}
@logger
end
@logger
end
def logger
self.class.logger
end
def self.get_rackup_or_rack_handler
defined?(::Rackup::Handler) && ::Rack.release >= '3' ? ::Rackup::Handler : ::Rack::Handler
end
private
def setup_rack_handler
# First try to set Rack handler via a special hook we honor
@rack_handler = if @app.respond_to?(:detect_rack_handler)
@app.detect_rack_handler
# If they aren't using our hook, try to use their @app.server settings
elsif @app.respond_to?(:server) and @app.server
# If :server isn't set, it returns an array of possibilities,
# sorted from most to least preferable.
if @app.server.is_a?(Array)
handler = nil
@app.server.each do |server|
begin
handler = self.class.get_rackup_or_rack_handler.get(server)
break
rescue LoadError, NameError
next
end
end
raise 'No available Rack handler (e.g. WEBrick, Puma, etc.) was found.' if handler.nil?
handler
# :server might be set explicitly to a single option like "mongrel"
else
self.class.get_rackup_or_rack_handler.get(@app.server)
end
# If all else fails, we'll use Puma
else
rack_server = JRUBY ? 'webrick' : 'puma'
self.class.get_rackup_or_rack_handler.get(rack_server)
end
end
def load_options(runtime_args)
@args = option_parser.parse!(runtime_args)
options.merge!(option_parser.options)
args
rescue OptionParser::MissingArgument => e
logger.warn "#{e}, run -h for options"
exit
end
def option_parser
@option_parser ||= Parser.new(app_name)
end
class Parser < OptionParser
attr_reader :command, :options
def initialize(app_name)
super("", 24, ' ')
self.banner = "Usage: #{app_name} [options]"
@options = {}
basename = app_name.gsub(/\W+/, "_")
on('-K', "--kill", "kill the running process and exit") { @command = :kill }
on('-S', "--status", "display the current running PID and URL then quit") { @command = :status }
string_option("-s", "--server SERVER", "serve using SERVER (thin/mongrel/webrick)", :rack_handler)
string_option("-o", "--host HOST", "listen on HOST (default: #{HOST})", :host)
string_option("-p", "--port PORT", "use PORT (default: #{PORT})", :port)
on("-x", "--no-proxy", "ignore env proxy settings (e.g. http_proxy)") { opts[:no_proxy] = true }
boolean_option("-F", "--foreground", "don't daemonize, run in the foreground", :foreground)
boolean_option("-L", "--no-launch", "don't launch the browser", :skip_launch)
boolean_option('-d', "--debug", "raise the log level to :debug (default: :info)", :debug)
string_option("--app-dir APP_DIR", "set the app dir where files are stored (default: ~/#{basename}/)", :app_dir)
string_option("-P", "--pid-file PID_FILE", "set the path to the pid file (default: app_dir/#{basename}.pid)", :pid_file)
string_option("--log-file LOG_FILE", "set the path to the log file (default: app_dir/#{basename}.log)", :log_file)
string_option("--url-file URL_FILE", "set the path to the URL file (default: app_dir/#{basename}.url)", :url_file)
string_option('-N NAMESPACE', "--namespace NAMESPACE", "set the Redis namespace", :redis_namespace)
string_option('-r redis-connection', "--redis redis-connection", "set the Redis connection string", :redis_conf)
string_option('-a url-prefix', "--append url-prefix", "set reverse_proxy friendly prefix to links", :url_prefix)
separator ""
separator "Common options:"
on_tail("-h", "--help", "Show this message") { @command = :help }
on_tail("--version", "Show version") { @command = :version }
end
def boolean_option(*argv)
k = argv.pop; on(*argv) { options[k] = true }
end
def string_option(*argv)
k = argv.pop; on(*argv) { |value| options[k] = value }
end
end
def kill_commands
WINDOWS ? [1] : [:INT, :TERM]
end
def kill_command
kill_commands[0]
end
def delete_pid!
File.delete(pid_file) if File.exist?(pid_file)
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/worker.rb | lib/resque/worker.rb | require 'time'
require 'set'
require 'redis/distributed'
module Resque
# A Resque Worker processes jobs. On platforms that support fork(2),
# the worker will fork off a child to process each job. This ensures
# a clean slate when beginning the next job and cuts down on gradual
# memory growth as well as low level failures.
#
# It also ensures workers are always listening to signals from you,
# their master, and can react accordingly.
class Worker
include Resque::Helpers
extend Resque::Helpers
include Resque::Logging
@@all_heartbeat_threads = []
def self.kill_all_heartbeat_threads
@@all_heartbeat_threads.each(&:kill).each(&:join)
@@all_heartbeat_threads = []
end
def redis
Resque.redis
end
alias :data_store :redis
def self.redis
Resque.redis
end
def self.data_store
self.redis
end
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
Resque.encode(object)
end
# Given a string, returns a Ruby object.
def decode(object)
Resque.decode(object)
end
attr_accessor :term_timeout
attr_accessor :pre_shutdown_timeout
attr_accessor :term_child_signal
# decide whether to use new_kill_child logic
attr_accessor :term_child
# should term kill workers gracefully (vs. immediately)
# Makes SIGTERM work like SIGQUIT
attr_accessor :graceful_term
# When set to true, forked workers will exit with `exit`, calling any `at_exit` code handlers that have been
# registered in the application. Otherwise, forked workers exit with `exit!`
attr_accessor :run_at_exit_hooks
attr_writer :fork_per_job
attr_writer :hostname
attr_writer :to_s
attr_writer :pid
# Returns an array of all worker objects.
def self.all
data_store.worker_ids.map { |id| find(id, :skip_exists => true) }.compact
end
# Returns an array of all worker objects currently processing
# jobs.
def self.working
names = all
return [] unless names.any?
reportedly_working = {}
begin
reportedly_working = data_store.workers_map(names).reject do |key, value|
value.nil? || value.empty?
end
rescue Redis::Distributed::CannotDistribute
names.each do |name|
value = data_store.get_worker_payload(name)
reportedly_working[name] = value unless value.nil? || value.empty?
end
end
reportedly_working.keys.map do |key|
worker = find(key.sub("worker:", ''), :skip_exists => true)
worker.job = worker.decode(reportedly_working[key])
worker
end.compact
end
# Returns a single worker object. Accepts a string id.
def self.find(worker_id, options = {})
skip_exists = options[:skip_exists]
if skip_exists || exists?(worker_id)
host, pid, queues_raw = worker_id.split(':', 3)
queues = queues_raw.split(',')
worker = new(*queues)
worker.hostname = host
worker.to_s = worker_id
worker.pid = pid.to_i
worker
else
nil
end
end
# Alias of `find`
def self.attach(worker_id)
find(worker_id)
end
# Given a string worker id, return a boolean indicating whether the
# worker exists
def self.exists?(worker_id)
data_store.worker_exists?(worker_id)
end
# Workers should be initialized with an array of string queue
# names. The order is important: a Worker will check the first
# queue given for a job. If none is found, it will check the
# second queue name given. If a job is found, it will be
# processed. Upon completion, the Worker will again check the
# first queue given, and so forth. In this way the queue list
# passed to a Worker on startup defines the priorities of queues.
#
# If passed a single "*", this Worker will operate on all queues
# in alphabetical order. Queues can be dynamically added or
# removed without needing to restart workers using this method.
#
# Workers should have `#prepare` called after they are initialized
# if you are running work on the worker.
def initialize(*queues)
@shutdown = nil
@paused = nil
@before_first_fork_hook_ran = false
@heartbeat_thread = nil
@heartbeat_thread_signal = nil
@last_state = :idle
verbose_value = ENV['LOGGING'] || ENV['VERBOSE']
self.verbose = verbose_value if verbose_value
self.very_verbose = ENV['VVERBOSE'] if ENV['VVERBOSE']
self.pre_shutdown_timeout = (ENV['RESQUE_PRE_SHUTDOWN_TIMEOUT'] || 0.0).to_f
self.term_timeout = (ENV['RESQUE_TERM_TIMEOUT'] || 4.0).to_f
self.term_child = ENV['TERM_CHILD']
self.graceful_term = ENV['GRACEFUL_TERM']
self.run_at_exit_hooks = ENV['RUN_AT_EXIT_HOOKS']
self.queues = queues
end
# Daemonizes the worker if ENV['BACKGROUND'] is set and writes
# the process id to ENV['PIDFILE'] if set. Should only be called
# once per worker.
def prepare
if ENV['BACKGROUND']
Process.daemon(true)
end
if ENV['PIDFILE']
File.open(ENV['PIDFILE'], 'w') { |f| f << pid }
end
self.reconnect if ENV['BACKGROUND']
end
WILDCARDS = ['*', '?', '{', '}', '[', ']'].freeze
def queues=(queues)
queues = (ENV["QUEUES"] || ENV['QUEUE']).to_s.split(',') if queues.empty?
queues = queues.map { |queue| queue.to_s.strip }
@skip_queues, @queues = queues.partition { |queue| queue.start_with?('!') }
@skip_queues.map! { |queue| queue[1..-1] }
# The behavior of `queues` is dependent on the value of `@has_dynamic_queues: if it's true, the method returns the result of filtering @queues with `glob_match`
# if it's false, the method returns @queues directly. Since `glob_match` will cause skipped queues to be filtered out, we want to make sure it's called if we have @skip_queues.any?
@has_dynamic_queues =
@skip_queues.any? || WILDCARDS.any? { |char| @queues.join.include?(char) }
validate_queues
end
# A worker must be given a queue, otherwise it won't know what to
# do with itself.
#
# You probably never need to call this.
def validate_queues
if @queues.nil? || @queues.empty?
raise NoQueueError.new("Please give each worker at least one queue.")
end
end
# Returns a list of queues to use when searching for a job.
# A splat ("*") means you want every queue (in alpha order) - this
# can be useful for dynamically adding new queues.
def queues
if @has_dynamic_queues
current_queues = Resque.queues
@queues.map { |queue| glob_match(current_queues, queue) }.flatten.uniq
else
@queues
end
end
def glob_match(list, pattern)
list.select do |queue|
File.fnmatch?(pattern, queue) &&
@skip_queues.none? { |skip_pattern| File.fnmatch?(skip_pattern, queue) }
end.sort
end
# This is the main workhorse method. Called on a Worker instance,
# it begins the worker life cycle.
#
# The following events occur during a worker's life cycle:
#
# 1. Startup: Signals are registered, dead workers are pruned,
# and this worker is registered.
# 2. Work loop: Jobs are pulled from a queue and processed.
# 3. Teardown: This worker is unregistered.
#
# Can be passed a float representing the polling frequency.
# The default is 5 seconds, but for a semi-active site you may
# want to use a smaller value.
#
# Also accepts a block which will be passed the job as soon as it
# has completed processing. Useful for testing.
def work(interval = 5.0, &block)
interval = Float(interval)
startup
loop do
break if shutdown?
unless work_one_job(&block)
state_change
break if interval.zero?
log_with_severity :debug, "Sleeping for #{interval} seconds"
procline paused? ? "Paused" : "Waiting for #{queues.join(',')}"
sleep interval
end
end
unregister_worker
run_hook :worker_exit
rescue Exception => exception
return if exception.class == SystemExit && !@child && run_at_exit_hooks
log_with_severity :error, "Failed to start worker : #{exception.inspect}"
log_with_severity :error, exception.backtrace.join("\n")
unregister_worker(exception)
run_hook :worker_exit
end
def work_one_job(job = nil, &block)
return false if paused?
return false unless job ||= reserve
working_on job
procline "Processing #{job.queue} since #{Time.now.to_i} [#{job.payload_class_name}]"
log_with_severity :info, "got: #{job.inspect}"
job.worker = self
if fork_per_job?
perform_with_fork(job, &block)
else
perform(job, &block)
end
done_working
true
end
# DEPRECATED. Processes a single job. If none is given, it will
# try to produce one. Usually run in the child.
def process(job = nil, &block)
return unless job ||= reserve
job.worker = self
working_on job
perform(job, &block)
ensure
done_working
end
# Reports the exception and marks the job as failed
def report_failed_job(job,exception)
log_with_severity :error, "#{job.inspect} failed: #{exception.inspect}"
begin
job.fail(exception)
rescue Object => exception
log_with_severity :error, "Received exception when reporting failure: #{exception.inspect}"
end
begin
failed!
rescue Object => exception
log_with_severity :error, "Received exception when increasing failed jobs counter (redis issue) : #{exception.inspect}"
end
end
# Processes a given job in the child.
def perform(job)
begin
if fork_per_job?
reconnect
run_hook :after_fork, job
end
job.perform
rescue Object => e
report_failed_job(job,e)
else
log_with_severity :info, "done: #{job.inspect}"
ensure
yield job if block_given?
end
end
# Attempts to grab a job off one of the provided queues. Returns
# nil if no job can be found.
def reserve
queues.each do |queue|
log_with_severity :debug, "Checking #{queue}"
if job = Resque.reserve(queue)
log_with_severity :debug, "Found job on #{queue}"
return job
end
end
nil
rescue Exception => e
log_with_severity :error, "Error reserving job: #{e.inspect}"
log_with_severity :error, e.backtrace.join("\n")
raise e
end
# Reconnect to Redis to avoid sharing a connection with the parent,
# retry up to 3 times with increasing delay before giving up.
def reconnect
tries = 0
begin
data_store.reconnect
rescue Redis::BaseConnectionError
if (tries += 1) <= 3
log_with_severity :error, "Error reconnecting to Redis; retrying"
sleep(tries)
retry
else
log_with_severity :error, "Error reconnecting to Redis; quitting"
raise
end
end
end
# Runs all the methods needed when a worker begins its lifecycle.
def startup
$0 = "resque: Starting"
enable_gc_optimizations
register_signal_handlers
start_heartbeat
prune_dead_workers
run_hook :before_first_fork
register_worker
# Fix buffering so we can `rake resque:work > resque.log` and
# get output from the child in there.
$stdout.sync = true
end
# Enables GC Optimizations if you're running REE.
# http://www.rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
def enable_gc_optimizations
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
end
# Registers the various signal handlers a worker responds to.
#
# TERM: Shutdown immediately, stop processing jobs.
# INT: Shutdown immediately, stop processing jobs.
# QUIT: Shutdown after the current job has finished processing.
# USR1: Kill the forked child immediately, continue processing jobs.
# USR2: Don't process any new jobs
# CONT: Start processing jobs again after a USR2
def register_signal_handlers
trap('TERM') { graceful_term ? shutdown : shutdown! }
trap('INT') { shutdown! }
begin
trap('QUIT') { shutdown }
if term_child
trap('USR1') { new_kill_child }
else
trap('USR1') { kill_child }
end
trap('USR2') { pause_processing }
trap('CONT') { unpause_processing }
rescue ArgumentError
log_with_severity :warn, "Signals QUIT, USR1, USR2, and/or CONT not supported."
end
log_with_severity :debug, "Registered signals"
end
def unregister_signal_handlers
trap('TERM') do
trap('TERM') do
# Ignore subsequent term signals
end
raise TermException.new("SIGTERM")
end
trap('INT', 'DEFAULT')
begin
trap('QUIT', 'DEFAULT')
trap('USR1', 'DEFAULT')
trap('USR2', 'DEFAULT')
rescue ArgumentError
end
end
# Schedule this worker for shutdown. Will finish processing the
# current job.
def shutdown
log_with_severity :info, 'Exiting...'
@shutdown = true
run_hook :shutdown
true
end
# Kill the child and shutdown immediately.
# If not forking, abort this process.
def shutdown!
shutdown
if term_child
if fork_per_job?
new_kill_child
else
# Raise TermException in the same process
trap('TERM') do
# ignore subsequent terms
end
raise TermException.new("SIGTERM")
end
else
kill_child
end
end
# Should this worker shutdown as soon as current job is finished?
def shutdown?
@shutdown
end
# Kills the forked child immediately, without remorse. The job it
# is processing will not be completed.
def kill_child
if @child
log_with_severity :debug, "Killing child at #{@child}"
if `ps -o pid,state -p #{@child}`
Process.kill("KILL", @child) rescue nil
else
log_with_severity :debug, "Child #{@child} not found, restarting."
shutdown
end
end
end
def heartbeat
data_store.heartbeat(self)
end
def remove_heartbeat
data_store.remove_heartbeat(self)
end
def heartbeat!(time = data_store.server_time)
data_store.heartbeat!(self, time)
end
def self.all_heartbeats
data_store.all_heartbeats
end
# Returns a list of workers that have sent a heartbeat in the past, but which
# already expired (does NOT include workers that have never sent a heartbeat at all).
def self.all_workers_with_expired_heartbeats
# Use `Worker.all_heartbeats` instead of `Worker.all`
# to prune workers which haven't been registered but have set a heartbeat.
# https://github.com/resque/resque/pull/1751
heartbeats = Worker.all_heartbeats
now = data_store.server_time
heartbeats.select do |id, heartbeat|
if heartbeat
seconds_since_heartbeat = (now - Time.parse(heartbeat)).to_i
seconds_since_heartbeat > Resque.prune_interval
else
false
end
end.each_key.map do |id|
# skip_exists must be true to include not registered workers
find(id, :skip_exists => true)
end
end
def start_heartbeat
remove_heartbeat
@heartbeat_thread_signal = Resque::ThreadSignal.new
@heartbeat_thread = Thread.new do
loop do
heartbeat!
signaled = @heartbeat_thread_signal.wait_for_signal(Resque.heartbeat_interval)
break if signaled
end
end
@@all_heartbeat_threads << @heartbeat_thread
end
# Kills the forked child immediately with minimal remorse. The job it
# is processing will not be completed. Send the child a TERM signal,
# wait <term_timeout> seconds, and then a KILL signal if it has not quit
# If pre_shutdown_timeout has been set to a positive number, it will allow
# the child that many seconds before sending the aforementioned TERM and KILL.
def new_kill_child
if @child
unless child_already_exited?
if pre_shutdown_timeout && pre_shutdown_timeout > 0.0
log_with_severity :debug, "Waiting #{pre_shutdown_timeout.to_f}s for child process to exit"
return if wait_for_child_exit(pre_shutdown_timeout)
end
log_with_severity :debug, "Sending TERM signal to child #{@child}"
Process.kill("TERM", @child)
if wait_for_child_exit(term_timeout)
return
else
log_with_severity :debug, "Sending KILL signal to child #{@child}"
Process.kill("KILL", @child)
end
else
log_with_severity :debug, "Child #{@child} already quit."
end
end
rescue SystemCallError
log_with_severity :error, "Child #{@child} already quit and reaped."
end
def child_already_exited?
Process.waitpid(@child, Process::WNOHANG)
end
def wait_for_child_exit(timeout)
(timeout * 10).round.times do |i|
sleep(0.1)
return true if child_already_exited?
end
false
end
# are we paused?
def paused?
@paused || redis.get('pause-all-workers').to_s.strip.downcase == 'true'
end
# Stop processing jobs after the current one has completed (if we're
# currently running one).
def pause_processing
_, self_write = IO.pipe
self_write.puts "USR2 received; pausing job processing"
run_hook :before_pause, self
@paused = true
end
# Start processing jobs again after a pause
def unpause_processing
_, self_write = IO.pipe
self_write.puts "CONT received; resuming job processing"
@paused = false
run_hook :after_pause, self
end
# Looks for any workers which should be running on this server
# and, if they're not, removes them from Redis.
#
# This is a form of garbage collection. If a server is killed by a
# hard shutdown, power failure, or something else beyond our
# control, the Resque workers will not die gracefully and therefore
# will leave stale state information in Redis.
#
# By checking the current Redis state against the actual
# environment, we can determine if Redis is old and clean it up a bit.
def prune_dead_workers
return unless data_store.acquire_pruning_dead_worker_lock(self, Resque.heartbeat_interval)
all_workers = Worker.all
known_workers = worker_pids
all_workers_with_expired_heartbeats = Worker.all_workers_with_expired_heartbeats
all_workers_with_expired_heartbeats.each do |worker|
# If the worker hasn't sent a heartbeat, remove it from the registry.
#
# If the worker hasn't ever sent a heartbeat, we won't remove it since
# the first heartbeat is sent before the worker is registred it means
# that this is a worker that doesn't support heartbeats, e.g., another
# client library or an older version of Resque. We won't touch these.
log_with_severity :info, "Pruning dead worker: #{worker}"
job_class = worker.job(false)['payload']['class'] rescue nil
worker.unregister_worker(PruneDeadWorkerDirtyExit.new(worker.to_s, job_class))
end
all_workers.each do |worker|
if all_workers_with_expired_heartbeats.include?(worker)
next
end
host, pid, worker_queues_raw = worker.id.split(':')
worker_queues = worker_queues_raw.split(",")
unless @queues.include?("*") || (worker_queues.to_set == @queues.to_set)
# If the worker we are trying to prune does not belong to the queues
# we are listening to, we should not touch it.
# Attempt to prune a worker from different queues may easily result in
# an unknown class exception, since that worker could easily be even
# written in different language.
next
end
next unless host == hostname
next if known_workers.include?(pid)
log_with_severity :debug, "Pruning dead worker: #{worker}"
worker.unregister_worker
end
end
# Registers ourself as a worker. Useful when entering the worker
# lifecycle on startup.
def register_worker
data_store.register_worker(self)
end
# Runs a named hook, passing along any arguments.
def run_hook(name, *args)
hooks = Resque.send(name)
return if hooks.empty?
return if name == :before_first_fork && @before_first_fork_hook_ran
msg = "Running #{name} hooks"
msg << " with #{args.inspect}" if args.any?
log_with_severity :info, msg
hooks.each do |hook|
args.any? ? hook.call(*args) : hook.call
@before_first_fork_hook_ran = true if name == :before_first_fork
end
end
def kill_background_threads
if @heartbeat_thread
@heartbeat_thread_signal.signal
@heartbeat_thread.join
end
end
# Unregisters ourself as a worker. Useful when shutting down.
def unregister_worker(exception = nil)
# If we're still processing a job, make sure it gets logged as a
# failure.
if (hash = processing) && !hash.empty?
job = Job.new(hash['queue'], hash['payload'])
# Ensure the proper worker is attached to this job, even if
# it's not the precise instance that died.
job.worker = self
begin
job.fail(exception || DirtyExit.new("Job still being processed"))
rescue RuntimeError => e
log_with_severity :error, e.message
end
end
kill_background_threads
data_store.unregister_worker(self) do |**opts|
Stat.clear("processed:#{self}", **opts)
Stat.clear("failed:#{self}", **opts)
end
rescue Exception => exception_while_unregistering
message = exception_while_unregistering.message
if exception
message += "\nOriginal Exception (#{exception.class}): #{exception.message}"
message += "\n #{exception.backtrace.join(" \n")}" if exception.backtrace
end
fail(exception_while_unregistering.class,
message,
exception_while_unregistering.backtrace)
end
# Given a job, tells Redis we're working on it. Useful for seeing
# what workers are doing and when.
def working_on(job)
data = encode \
:queue => job.queue,
:run_at => Time.now.utc.iso8601,
:payload => job.payload
data_store.set_worker_payload(self,data)
state_change
end
# Called when we are done working - clears our `working_on` state
# and tells Redis we processed a job.
def done_working
data_store.worker_done_working(self) do |**opts|
processed!(**opts)
end
end
def state_change
current_state = state
if current_state != @last_state
run_hook :queue_empty if current_state == :idle
@last_state = current_state
end
end
# How many jobs has this worker processed? Returns an int.
def processed
Stat["processed:#{self}"]
end
# Tell Redis we've processed a job.
def processed!(**opts)
Stat.incr("processed", 1, **opts)
Stat.incr("processed:#{self}", 1, **opts)
end
# How many failed jobs has this worker seen? Returns an int.
def failed
Stat["failed:#{self}"]
end
# Tells Redis we've failed a job.
def failed!
Stat << "failed"
Stat << "failed:#{self}"
end
# What time did this worker start? Returns an instance of `Time`
def started
data_store.worker_start_time(self)
end
# Tell Redis we've started
def started!
data_store.worker_started(self)
end
# Returns a hash explaining the Job we're currently processing, if any.
def job(reload = true)
@job = nil if reload
@job ||= decode(data_store.get_worker_payload(self)) || {}
end
attr_writer :job
alias_method :processing, :job
# Boolean - true if working, false if not
def working?
state == :working
end
# Boolean - true if idle, false if not
def idle?
state == :idle
end
def fork_per_job?
return @fork_per_job if defined?(@fork_per_job)
@fork_per_job = ENV["FORK_PER_JOB"] != 'false' && Kernel.respond_to?(:fork)
end
# Returns a symbol representing the current worker state,
# which can be either :working or :idle
def state
data_store.get_worker_payload(self) ? :working : :idle
end
# Is this worker the same as another worker?
def ==(other)
to_s == other.to_s
end
def inspect
"#<Worker #{to_s}>"
end
# The string representation is the same as the id for this worker
# instance. Can be used with `Worker.find`.
def to_s
@to_s ||= "#{hostname}:#{pid}:#{@queues.join(',')}"
end
alias_method :id, :to_s
# chomp'd hostname of this worker's machine
def hostname
@hostname ||= Socket.gethostname
end
# Returns Integer PID of running worker
def pid
@pid ||= Process.pid
end
# Returns an Array of string pids of all the other workers on this
# machine. Useful when pruning dead workers on startup.
def worker_pids
if RUBY_PLATFORM =~ /solaris/
solaris_worker_pids
elsif RUBY_PLATFORM =~ /mingw32/
windows_worker_pids
else
linux_worker_pids
end
end
# Returns an Array of string pids of all the other workers on this
# machine. Useful when pruning dead workers on startup.
def windows_worker_pids
tasklist_output = `tasklist /FI "IMAGENAME eq ruby.exe" /FO list`.encode("UTF-8", Encoding.locale_charmap)
tasklist_output.split($/).select { |line| line =~ /^PID:/ }.collect { |line| line.gsub(/PID:\s+/, '') }
end
# Find Resque worker pids on Linux and OS X.
#
def linux_worker_pids
`ps -A -o pid,command | grep -E "[r]esque:work|[r]esque:\sStarting|[r]esque-[0-9]" | grep -v "resque-web"`.split("\n").map do |line|
line.split(' ')[0]
end
end
# Find Resque worker pids on Solaris.
#
# Returns an Array of string pids of all the other workers on this
# machine. Useful when pruning dead workers on startup.
def solaris_worker_pids
`ps -A -o pid,comm | grep "[r]uby" | grep -v "resque-web"`.split("\n").map do |line|
real_pid = line.split(' ')[0]
pargs_command = `pargs -a #{real_pid} 2>/dev/null | grep [r]esque | grep -v "resque-web"`
if pargs_command.split(':')[1] == " resque-#{Resque::VERSION}"
real_pid
end
end.compact
end
# Given a string, sets the procline ($0) and logs.
# Procline is always in the format of:
# RESQUE_PROCLINE_PREFIXresque-VERSION: STRING
def procline(string)
$0 = "#{ENV['RESQUE_PROCLINE_PREFIX']}resque-#{Resque::VERSION}: #{string}"
log_with_severity :debug, $0
end
def log(message)
info(message)
end
def log!(message)
debug(message)
end
attr_reader :verbose, :very_verbose
def verbose=(value);
if value && !very_verbose
Resque.logger.formatter = VerboseFormatter.new
Resque.logger.level = Logger::INFO
elsif !value
Resque.logger.formatter = QuietFormatter.new
end
@verbose = value
end
def very_verbose=(value)
if value
Resque.logger.formatter = VeryVerboseFormatter.new
Resque.logger.level = Logger::DEBUG
elsif !value && verbose
Resque.logger.formatter = VerboseFormatter.new
Resque.logger.level = Logger::INFO
else
Resque.logger.formatter = QuietFormatter.new
end
@very_verbose = value
end
private
def perform_with_fork(job, &block)
run_hook :before_fork, job
begin
@child = fork do
unregister_signal_handlers if term_child
perform(job, &block)
exit! unless run_at_exit_hooks
end
rescue NotImplementedError
@fork_per_job = false
perform(job, &block)
return
end
srand # Reseeding
procline "Forked #{@child} at #{Time.now.to_i}"
begin
Process.waitpid(@child)
rescue SystemCallError
nil
end
job.fail(DirtyExit.new("Child process received unhandled signal #{$?}", $?)) if $?.signaled?
@child = nil
end
def log_with_severity(severity, message)
Logging.log(severity, message)
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure.rb | lib/resque/failure.rb | module Resque
# The Failure module provides an interface for working with different
# failure backends.
#
# You can use it to query the failure backend without knowing which specific
# backend is being used. For instance, the Resque web app uses it to display
# stats and other information.
module Failure
# Creates a new failure, which is delegated to the appropriate backend.
#
# Expects a hash with the following keys:
# :exception - The Exception object
# :worker - The Worker object who is reporting the failure
# :queue - The string name of the queue from which the job was pulled
# :payload - The job's payload
def self.create(options = {})
backend.new(*options.values_at(:exception, :worker, :queue, :payload)).save
end
#
# Sets the current backend. Expects a class descendent of
# `Resque::Failure::Base`.
#
# Example use:
# require 'resque/failure/airbrake'
# Resque::Failure.backend = Resque::Failure::Airbrake
def self.backend=(backend)
@backend = backend
end
self.backend = nil
# Returns the current backend class. If none has been set, falls
# back to `Resque::Failure::Redis`
def self.backend
return @backend if @backend
case ENV['FAILURE_BACKEND']
when 'redis_multi_queue'
require 'resque/failure/redis_multi_queue'
@backend = Failure::RedisMultiQueue
when 'redis', nil
require 'resque/failure/redis'
@backend = Failure::Redis
else
raise ArgumentError, "invalid failure backend: #{FAILURE_BACKEND}"
end
end
# Obtain the failure queue name for a given job queue
def self.failure_queue_name(job_queue_name)
name = "#{job_queue_name}_failed"
Resque.data_store.add_failed_queue(name)
name
end
# Obtain the job queue name for a given failure queue
def self.job_queue_name(failure_queue_name)
failure_queue_name.sub(/_failed$/, '')
end
# Returns an array of all the failed queues in the system
def self.queues
backend.queues
end
# Returns the int count of how many failures we have seen.
def self.count(queue = nil, class_name = nil)
backend.count(queue, class_name)
end
# Returns an array of all the failures, paginated.
#
# `offset` is the int of the first item in the page, `limit` is the
# number of items to return.
def self.all(offset = 0, limit = 1, queue = nil)
backend.all(offset, limit, queue)
end
# Iterate across all failures with the given options
def self.each(offset = 0, limit = self.count, queue = nil, class_name = nil, order = 'desc', &block)
backend.each(offset, limit, queue, class_name, order, &block)
end
# The string url of the backend's web interface, if any.
def self.url
backend.url
end
# Clear all failure jobs
def self.clear(queue = nil)
backend.clear(queue)
end
def self.clear_retried
each do |index, job|
remove(index) unless job['retried_at'].nil?
end
end
def self.requeue(id, queue = nil)
backend.requeue(id, queue)
end
def self.remove(id, queue = nil)
backend.remove(id, queue)
end
# Requeues all failed jobs in a specific queue.
# Queue name should be a string.
def self.requeue_queue(queue)
backend.requeue_queue(queue)
end
# Requeues all failed jobs
def self.requeue_all
backend.requeue_all
end
# Removes all failed jobs in a specific queue.
# Queue name should be a string.
def self.remove_queue(queue)
backend.remove_queue(queue)
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/server.rb | lib/resque/server.rb | require 'sinatra/base'
require 'tilt/erb'
require 'resque'
require 'resque/server_helper'
require 'resque/version'
require 'time'
require 'yaml'
if defined?(Encoding) && Encoding.default_external != Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8
end
module Resque
class Server < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/server/views"
if respond_to? :public_folder
set :public_folder, "#{dir}/server/public"
else
set :public, "#{dir}/server/public"
end
set :static, true
helpers do
include Resque::ServerHelper
end
def show(page, layout = true)
response["Cache-Control"] = "max-age=0, private, must-revalidate"
begin
erb page.to_sym, {:layout => layout}, :resque => Resque
rescue Errno::ECONNREFUSED
erb :error, {:layout => false}, :error => "Can't connect to Redis! (#{Resque.redis_id})"
end
end
def show_for_polling(page)
content_type "text/html"
@polling = true
show(page.to_sym, false).gsub(/\s{1,}/, ' ')
end
# to make things easier on ourselves
get "/?" do
redirect url_path(:overview)
end
%w( overview workers ).each do |page|
get "/#{page}.poll/?" do
show_for_polling(page)
end
get "/#{page}/:id.poll/?" do
show_for_polling(page)
end
end
%w( overview queues working workers key ).each do |page|
get "/#{page}/?" do
show page
end
get "/#{page}/:id/?" do
show page
end
end
post "/queues/:id/remove" do
Resque.remove_queue(params[:id])
redirect u('queues')
end
get "/failed/?" do
if Resque::Failure.url
redirect Resque::Failure.url
else
show :failed
end
end
get "/failed/:queue" do
if Resque::Failure.url
redirect Resque::Failure.url
else
show :failed
end
end
post "/failed/clear" do
Resque::Failure.clear
redirect u('failed')
end
post "/failed/clear_retried" do
Resque::Failure.clear_retried
redirect u('failed')
end
post "/failed/:queue/clear" do
Resque::Failure.clear params[:queue]
redirect u('failed')
end
post "/failed/requeue/all" do
Resque::Failure.requeue_all
redirect u('failed')
end
post "/failed/:queue/requeue/all" do
Resque::Failure.requeue_queue Resque::Failure.job_queue_name(params[:queue])
redirect url_path("/failed/#{params[:queue]}")
end
get "/failed/requeue/:index/?" do
Resque::Failure.requeue(params[:index])
if request.xhr?
return Resque::Failure.all(params[:index])['retried_at']
else
redirect u('failed')
end
end
get "/failed/:queue/requeue/:index/?" do
Resque::Failure.requeue(params[:index], params[:queue])
if request.xhr?
return Resque::Failure.all(params[:index],1,params[:queue])['retried_at']
else
redirect url_path("/failed/#{params[:queue]}")
end
end
get "/failed/remove/:index/?" do
Resque::Failure.remove(params[:index])
redirect u('failed')
end
get "/failed/:queue/remove/:index/?" do
Resque::Failure.remove(params[:index], params[:queue])
redirect url_path("/failed/#{params[:queue]}")
end
get "/stats/?" do
redirect url_path("/stats/resque")
end
get "/stats/:id/?" do
show :stats
end
get "/stats/keys/:key/?" do
show :stats
end
get "/stats.txt/?" do
info = Resque.info
stats = []
stats << "resque.pending=#{info[:pending]}"
stats << "resque.processed+=#{info[:processed]}"
stats << "resque.failed+=#{info[:failed]}"
stats << "resque.workers=#{info[:workers]}"
stats << "resque.working=#{info[:working]}"
Resque.queues.each do |queue|
stats << "queues.#{queue}=#{Resque.size(queue)}"
end
content_type 'text/html'
stats.join "\n"
end
def resque
Resque
end
def self.tabs
@tabs ||= ["Overview", "Working", "Failed", "Queues", "Workers", "Stats"]
end
def self.url_prefix=(url_prefix)
@url_prefix = url_prefix
end
def self.url_prefix
(@url_prefix.nil? || @url_prefix.empty?) ? '' : @url_prefix + '/'
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/server_helper.rb | lib/resque/server_helper.rb | require 'rack/utils'
module Resque
module ServerHelper
include Rack::Utils
alias_method :h, :escape_html
def current_section
url_path request.path_info.sub('/','').split('/')[0].downcase
end
def current_page
url_path request.path_info.sub('/','')
end
def url_path(*path_parts)
[ url_prefix, path_prefix, path_parts ].join("/").squeeze('/')
end
alias_method :u, :url_path
def path_prefix
request.env['SCRIPT_NAME']
end
def class_if_current(path = '')
'class="current"' if current_page[0, path.size] == path
end
def tab(name)
dname = name.to_s.downcase
path = url_path(dname)
"<li #{class_if_current(path)}><a href='#{path.gsub(" ", "_")}'>#{name}</a></li>"
end
def tabs
Resque::Server.tabs
end
def url_prefix
Resque::Server.url_prefix
end
def redis_get_size(key)
case Resque.redis.type(key)
when 'none'
0
when 'hash'
Resque.redis.hlen(key)
when 'list'
Resque.redis.llen(key)
when 'set'
Resque.redis.scard(key)
when 'string'
Resque.redis.get(key).length
when 'zset'
Resque.redis.zcard(key)
end
end
def redis_get_value_as_array(key, start=0)
case Resque.redis.type(key)
when 'none'
[]
when 'hash'
Resque.redis.hgetall(key).to_a[start..(start + 20)]
when 'list'
Resque.redis.lrange(key, start, start + 20)
when 'set'
Resque.redis.smembers(key)[start..(start + 20)]
when 'string'
[Resque.redis.get(key)]
when 'zset'
Resque.redis.zrange(key, start, start + 20)
end
end
def show_args(args)
Array(args).map do |a|
a.to_yaml
end.join("\n")
rescue
args.to_s
end
def worker_hosts
@worker_hosts ||= worker_hosts!
end
def worker_hosts!
hosts = Hash.new { [] }
Resque.workers.each do |worker|
host, _ = worker.to_s.split(':')
hosts[host] += [worker.to_s]
end
hosts
end
def partial?
@partial
end
def partial(template, local_vars = {})
@partial = true
erb(template.to_sym, {:layout => false}, local_vars)
ensure
@partial = false
end
def poll
if defined?(@polling) && @polling
text = "Last Updated: #{Time.now.strftime("%H:%M:%S")}"
else
text = "<a href='#{u(request.path_info)}.poll' rel='poll'>Live Poll!!</a>"
end
"<p class='poll'>#{text}</p>"
end
####################
#failed.erb helpers#
####################
def failed_date_format
"%Y/%m/%d %T %z"
end
def failed_multiple_queues?
return @multiple_failed_queues if defined?(@multiple_failed_queues)
@multiple_failed_queues = Resque::Failure.queues.size > 1 ||
(defined?(Resque::Failure::RedisMultiQueue) && Resque::Failure.backend == Resque::Failure::RedisMultiQueue)
end
def failed_size
@failed_size ||= Resque::Failure.count(params[:queue], params[:class])
end
def failed_per_page
@failed_per_page = if params[:class]
failed_size
else
20
end
end
def failed_start_at
params[:start].to_i
end
def failed_end_at
if failed_start_at + failed_per_page > failed_size
failed_size
else
failed_start_at + failed_per_page - 1
end
end
def failed_order
params[:order] || 'desc'
end
def failed_class_counts(queue = params[:queue])
classes = Hash.new(0)
Resque::Failure.each(0, Resque::Failure.count(queue), queue) do |_, item|
class_name = item['payload']['class'] if item['payload']
class_name ||= "nil"
classes[class_name] += 1
end
classes
end
def page_entries_info(start, stop, size, name = nil)
if size == 0
name ? "No #{name}s" : '<b>0</b>'
elsif size == 1
'Showing <b>1</b>' + (name ? " #{name}" : '')
elsif size > failed_per_page
"Showing #{start}-#{stop} of <b>#{size}</b>" + (name ? " #{name}s" : '')
else
"Showing #{start} to <b>#{size - 1}</b>" + (name ? " #{name}s" : '')
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/tasks.rb | lib/resque/tasks.rb | # require 'resque/tasks'
# will give you the resque tasks
namespace :resque do
task :setup
desc "Start a Resque worker"
task :work => [ :preload, :setup ] do
require 'resque'
begin
worker = Resque::Worker.new
rescue Resque::NoQueueError
abort "set QUEUE env var, e.g. $ QUEUE=critical,high rake resque:work"
end
worker.prepare
worker.log "Starting worker #{worker}"
worker.work(ENV['INTERVAL'] || 5) # interval, will block
end
desc "Start multiple Resque workers. Should only be used in dev mode."
task :workers do
threads = []
if ENV['COUNT'].to_i < 1
abort "set COUNT env var, e.g. $ COUNT=2 rake resque:workers"
end
ENV['COUNT'].to_i.times do
threads << Thread.new do
system "rake resque:work"
end
end
threads.each { |thread| thread.join }
end
# Preload app files if this is Rails
task :preload => :setup do
if defined?(Rails) && Rails.respond_to?(:application)
if Rails.application.config.eager_load
ActiveSupport.run_load_hooks(:before_eager_load, Rails.application)
Rails.application.config.eager_load_namespaces.each(&:eager_load!)
end
end
end
namespace :failures do
desc "Sort the 'failed' queue for the redis_multi_queue failure backend"
task :sort do
require 'resque'
require 'resque/failure/redis'
warn "Sorting #{Resque::Failure.count} failures..."
Resque::Failure.each(0, Resque::Failure.count) do |_, failure|
data = Resque.encode(failure)
Resque.redis.rpush(Resque::Failure.failure_queue_name(failure['queue']), data)
end
warn "done!"
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/data_store.rb | lib/resque/data_store.rb | module Resque
# An interface between Resque's persistence and the actual
# implementation.
class DataStore
extend Forwardable
HEARTBEAT_KEY = "workers:heartbeat"
def initialize(redis)
@redis = redis
@queue_access = QueueAccess.new(@redis)
@failed_queue_access = FailedQueueAccess.new(@redis)
@workers = Workers.new(@redis)
@stats_access = StatsAccess.new(@redis)
end
def_delegators :@queue_access, :push_to_queue,
:pop_from_queue,
:queue_size,
:peek_in_queue,
:queue_names,
:remove_queue,
:everything_in_queue,
:remove_from_queue,
:watch_queue,
:list_range
def_delegators :@failed_queue_access, :add_failed_queue,
:remove_failed_queue,
:num_failed,
:failed_queue_names,
:push_to_failed_queue,
:clear_failed_queue,
:update_item_in_failed_queue,
:remove_from_failed_queue
def_delegators :@workers, :worker_ids,
:workers_map,
:get_worker_payload,
:worker_exists?,
:register_worker,
:worker_started,
:unregister_worker,
:heartbeat,
:heartbeat!,
:remove_heartbeat,
:all_heartbeats,
:acquire_pruning_dead_worker_lock,
:set_worker_payload,
:worker_start_time,
:worker_done_working
def_delegators :@stats_access, :clear_stat,
:decrement_stat,
:increment_stat,
:stat
def decremet_stat(*args)
warn '[Resque] [Deprecation] Resque::DataStore #decremet_stat method is deprecated (please use #decrement_stat)'
decrement_stat(*args)
end
# Compatibility with any non-Resque classes that were using Resque.redis as a way to access Redis
def method_missing(sym,*args,&block)
# TODO: deprecation warning?
@redis.send(sym,*args,&block)
end
# make use respond like redis
def respond_to?(method,include_all=false)
@redis.respond_to?(method,include_all) || super
end
# Get a string identifying the underlying server.
# Probably should be private, but was public so must stay public
def identifier
@redis.inspect
end
# Force a reconnect to Redis without closing the connection in the parent
# process after a fork.
def reconnect
@redis.disconnect!
@redis.ping
nil
end
# Returns an array of all known Resque keys in Redis. Redis' KEYS operation
# is O(N) for the keyspace, so be careful - this can be slow for big databases.
def all_resque_keys
@redis.keys("*").map do |key|
key.sub("#{@redis.namespace}:", '')
end
end
def server_time
time, _ = @redis.time
Time.at(time)
end
class QueueAccess
def initialize(redis)
@redis = redis
end
def push_to_queue(queue,encoded_item)
@redis.pipelined do |piped|
watch_queue(queue, redis: piped)
piped.rpush redis_key_for_queue(queue), encoded_item
end
end
# Pop whatever is on queue
def pop_from_queue(queue)
@redis.lpop(redis_key_for_queue(queue))
end
# Get the number of items in the queue
def queue_size(queue)
@redis.llen(redis_key_for_queue(queue)).to_i
end
# Examine items in the queue.
#
# NOTE: if count is 1, you will get back an object, otherwise you will
# get an Array. I'm not making this up.
def peek_in_queue(queue, start = 0, count = 1)
list_range(redis_key_for_queue(queue), start, count)
end
def queue_names
Array(@redis.smembers(:queues))
end
def remove_queue(queue)
@redis.pipelined do |piped|
piped.srem(:queues, [queue.to_s])
piped.del(redis_key_for_queue(queue))
end
end
def everything_in_queue(queue)
@redis.lrange(redis_key_for_queue(queue), 0, -1)
end
# Remove data from the queue, if it's there, returning the number of removed elements
def remove_from_queue(queue,data)
@redis.lrem(redis_key_for_queue(queue), 0, data)
end
# Private: do not call
def watch_queue(queue, redis: @redis)
redis.sadd(:queues, [queue.to_s])
end
# Private: do not call
def list_range(key, start = 0, count = 1)
if count == 1
@redis.lindex(key, start)
else
Array(@redis.lrange(key, start, start+count-1))
end
end
private
def redis_key_for_queue(queue)
"queue:#{queue}"
end
end
class FailedQueueAccess
def initialize(redis)
@redis = redis
end
def add_failed_queue(failed_queue_name)
@redis.sadd(:failed_queues, [failed_queue_name])
end
def remove_failed_queue(failed_queue_name=:failed)
@redis.del(failed_queue_name)
end
def num_failed(failed_queue_name=:failed)
@redis.llen(failed_queue_name).to_i
end
def failed_queue_names(find_queue_names_in_key=nil)
if find_queue_names_in_key.nil?
[:failed]
else
Array(@redis.smembers(find_queue_names_in_key))
end
end
def push_to_failed_queue(data,failed_queue_name=:failed)
@redis.rpush(failed_queue_name,data)
end
def clear_failed_queue(failed_queue_name=:failed)
@redis.del(failed_queue_name)
end
def update_item_in_failed_queue(index_in_failed_queue,new_item_data,failed_queue_name=:failed)
@redis.lset(failed_queue_name, index_in_failed_queue, new_item_data)
end
def remove_from_failed_queue(index_in_failed_queue,failed_queue_name=nil)
failed_queue_name ||= :failed
hopefully_unique_value_we_can_use_to_delete_job = ""
@redis.lset(failed_queue_name, index_in_failed_queue, hopefully_unique_value_we_can_use_to_delete_job)
@redis.lrem(failed_queue_name, 1, hopefully_unique_value_we_can_use_to_delete_job)
end
end
class Workers
def initialize(redis)
@redis = redis
end
def worker_ids
Array(@redis.smembers(:workers))
end
# Given a list of worker ids, returns a map of those ids to the worker's value
# in redis, even if that value maps to nil
def workers_map(worker_ids)
redis_keys = worker_ids.map { |id| "worker:#{id}" }
@redis.mapped_mget(*redis_keys)
end
# return the worker's payload i.e. job
def get_worker_payload(worker_id)
@redis.get("worker:#{worker_id}")
end
def worker_exists?(worker_id)
@redis.sismember(:workers, worker_id)
end
def register_worker(worker)
@redis.pipelined do |piped|
piped.sadd(:workers, [worker.id])
worker_started(worker, redis: piped)
end
end
def worker_started(worker, redis: @redis)
redis.set(redis_key_for_worker_start_time(worker), Time.now.to_s)
end
def unregister_worker(worker, &block)
@redis.pipelined do |piped|
piped.srem(:workers, [worker.id])
piped.del(redis_key_for_worker(worker))
piped.del(redis_key_for_worker_start_time(worker))
piped.hdel(HEARTBEAT_KEY, worker.to_s)
block.call redis: piped
end
end
def remove_heartbeat(worker)
@redis.hdel(HEARTBEAT_KEY, worker.to_s)
end
def heartbeat(worker)
heartbeat = @redis.hget(HEARTBEAT_KEY, worker.to_s)
heartbeat && Time.parse(heartbeat)
end
def heartbeat!(worker, time)
@redis.hset(HEARTBEAT_KEY, worker.to_s, time.iso8601)
end
def all_heartbeats
@redis.hgetall(HEARTBEAT_KEY)
end
def acquire_pruning_dead_worker_lock(worker, expiry)
@redis.set(redis_key_for_worker_pruning, worker.to_s, :ex => expiry, :nx => true)
end
def set_worker_payload(worker, data)
@redis.set(redis_key_for_worker(worker), data)
end
def worker_start_time(worker)
@redis.get(redis_key_for_worker_start_time(worker))
end
def worker_done_working(worker, &block)
@redis.pipelined do |piped|
piped.del(redis_key_for_worker(worker))
block.call redis: piped
end
end
private
def redis_key_for_worker(worker)
"worker:#{worker}"
end
def redis_key_for_worker_start_time(worker)
"#{redis_key_for_worker(worker)}:started"
end
def redis_key_for_worker_pruning
"pruning_dead_workers_in_progress"
end
end
class StatsAccess
def initialize(redis)
@redis = redis
end
def stat(stat)
@redis.get("stat:#{stat}").to_i
end
def increment_stat(stat, by = 1, redis: @redis)
redis.incrby("stat:#{stat}", by)
end
def decremet_stat(stat, by = 1)
@redis.decrby("stat:#{stat}", by)
end
def clear_stat(stat, redis: @redis)
redis.del("stat:#{stat}")
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/job.rb | lib/resque/job.rb | module Resque
# A Resque::Job represents a unit of work. Each job lives on a
# single queue and has an associated payload object. The payload
# is a hash with two attributes: `class` and `args`. The `class` is
# the name of the Ruby class which should be used to run the
# job. The `args` are an array of arguments which should be passed
# to the Ruby class's `perform` class-level method.
#
# You can manually run a job using this code:
#
# job = Resque::Job.reserve(:high)
# klass = Resque::Job.constantize(job.payload['class'])
# klass.perform(*job.payload['args'])
class Job
include Helpers
extend Helpers
def redis
Resque.redis
end
alias :data_store :redis
def self.redis
Resque.redis
end
def self.data_store
self.redis
end
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
Resque.encode(object)
end
# Given a string, returns a Ruby object.
def decode(object)
Resque.decode(object)
end
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def self.encode(object)
Resque.encode(object)
end
# Given a string, returns a Ruby object.
def self.decode(object)
Resque.decode(object)
end
# Given a word with dashes, returns a camel cased version of it.
def classify(dashed_word)
Resque.classify(dashed_word)
end
# Tries to find a constant with the name specified in the argument string
def constantize(camel_cased_word)
Resque.constantize(camel_cased_word)
end
# Raise Resque::Job::DontPerform from a before_perform hook to
# abort the job.
DontPerform = Class.new(StandardError)
# The worker object which is currently processing this job.
attr_accessor :worker
# The name of the queue from which this job was pulled (or is to be
# placed)
attr_reader :queue
# This job's associated payload object.
attr_reader :payload
def initialize(queue, payload)
@queue = queue
@payload = payload
@failure_hooks_ran = false
end
# Creates a job by placing it on a queue. Expects a string queue
# name, a string class name, and an optional array of arguments to
# pass to the class' `perform` method.
#
# Raises an exception if no queue or class is given.
def self.create(queue, klass, *args)
Resque.validate(klass, queue)
if Resque.inline?
# Instantiating a Resque::Job and calling perform on it so callbacks run
# decode(encode(args)) to ensure that args are normalized in the same manner as a non-inline job
new(:inline, {'class' => klass, 'args' => decode(encode(args))}).perform
else
Resque.push(queue, :class => klass.to_s, :args => args)
end
end
# Removes a job from a queue. Expects a string queue name, a
# string class name, and, optionally, args.
#
# Returns the number of jobs destroyed.
#
# If no args are provided, it will remove all jobs of the class
# provided.
#
# That is, for these two jobs:
#
# { 'class' => 'UpdateGraph', 'args' => ['defunkt'] }
# { 'class' => 'UpdateGraph', 'args' => ['mojombo'] }
#
# The following call will remove both:
#
# Resque::Job.destroy(queue, 'UpdateGraph')
#
# Whereas specifying args will only remove the 2nd job:
#
# Resque::Job.destroy(queue, 'UpdateGraph', 'mojombo')
#
# This method can be potentially very slow and memory intensive,
# depending on the size of your queue, as it loads all jobs into
# a Ruby array before processing.
def self.destroy(queue, klass, *args)
klass = klass.to_s
destroyed = 0
if args.empty?
data_store.everything_in_queue(queue).each do |string|
if decode(string)['class'] == klass
destroyed += data_store.remove_from_queue(queue,string).to_i
end
end
else
destroyed += data_store.remove_from_queue(queue, encode(:class => klass, :args => args))
end
destroyed
end
# Given a string queue name, returns an instance of Resque::Job
# if any jobs are available. If not, returns nil.
def self.reserve(queue)
return unless payload = Resque.pop(queue)
new(queue, payload)
end
# Attempts to perform the work represented by this job instance.
# Calls #perform on the class given in the payload with the
# arguments given in the payload.
def perform
job = payload_class
job_args = args || []
job_was_performed = false
begin
# Execute before_perform hook. Abort the job gracefully if
# Resque::Job::DontPerform is raised.
begin
before_hooks.each do |hook|
job.send(hook, *job_args)
end
rescue DontPerform
return false
end
# Execute the job. Do it in an around_perform hook if available.
if around_hooks.empty?
job.perform(*job_args)
job_was_performed = true
else
# We want to nest all around_perform plugins, with the last one
# finally calling perform
stack = around_hooks.reverse.inject(nil) do |last_hook, hook|
if last_hook
lambda do
job.send(hook, *job_args) { last_hook.call }
end
else
lambda do
job.send(hook, *job_args) do
result = job.perform(*job_args)
job_was_performed = true
result
end
end
end
end
stack.call
end
# Execute after_perform hook
after_hooks.each do |hook|
job.send(hook, *job_args)
end
# Return true if the job was performed
return job_was_performed
# If an exception occurs during the job execution, look for an
# on_failure hook then re-raise.
rescue Object => e
run_failure_hooks(e)
raise e
end
end
# Returns the actual class constant represented in this job's payload.
def payload_class
@payload_class ||= constantize(@payload['class'])
end
# Returns the payload class as a string without raising NameError
def payload_class_name
payload_class.to_s
rescue NameError
'No Name'
end
def has_payload_class?
payload_class != Object
rescue NameError
false
end
# Returns an array of args represented in this job's payload.
def args
@payload['args']
end
# Given an exception object, hands off the needed parameters to
# the Failure module.
def fail(exception)
begin
run_failure_hooks(exception)
rescue Exception => e
raise e
ensure
Failure.create \
:payload => payload,
:exception => exception,
:worker => worker,
:queue => queue
end
end
# Creates an identical job, essentially placing this job back on
# the queue.
def recreate
self.class.create(queue, payload_class, *args)
end
# String representation
def inspect
obj = @payload
"(Job{%s} | %s | %s)" % [ @queue, obj['class'], obj['args'].inspect ]
end
# Equality
def ==(other)
queue == other.queue &&
payload_class == other.payload_class &&
args == other.args
end
def before_hooks
@before_hooks ||= Plugin.before_hooks(payload_class)
end
def around_hooks
@around_hooks ||= Plugin.around_hooks(payload_class)
end
def after_hooks
@after_hooks ||= Plugin.after_hooks(payload_class)
end
def failure_hooks
@failure_hooks ||= Plugin.failure_hooks(payload_class)
end
def run_failure_hooks(exception)
begin
job_args = args || []
if has_payload_class?
failure_hooks.each { |hook| payload_class.send(hook, exception, *job_args) } unless @failure_hooks_ran
end
rescue Exception => e
error_message = "Additional error (#{e.class}: #{e}) occurred in running failure hooks for job #{inspect}\n" \
"Original error that caused job failure was #{e.class}: #{exception.class}: #{exception.message}"
raise RuntimeError.new(error_message)
ensure
@failure_hooks_ran = true
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/vendor/utf8_util.rb | lib/resque/vendor/utf8_util.rb | module UTF8Util
# use '?' intsead of the unicode replace char, since that is 3 bytes
# and can increase the string size if it's done a lot
REPLACEMENT_CHAR = "?"
# Replace invalid UTF-8 character sequences with a replacement character
#
# Returns self as valid UTF-8.
def self.clean!(str)
return str if str.encoding.to_s == "UTF-8"
str.force_encoding("binary").encode("UTF-8", :invalid => :replace, :undef => :replace, :replace => REPLACEMENT_CHAR)
end
# Replace invalid UTF-8 character sequences with a replacement character
#
# Returns a copy of this String as valid UTF-8.
def self.clean(str)
clean!(str.dup)
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/log_formatters/very_verbose_formatter.rb | lib/resque/log_formatters/very_verbose_formatter.rb | module Resque
class VeryVerboseFormatter
def call(serverity, datetime, progname, msg)
time = Time.now.strftime('%H:%M:%S %Y-%m-%d')
"** [#{time}] #$$: #{msg}\n"
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/log_formatters/quiet_formatter.rb | lib/resque/log_formatters/quiet_formatter.rb | module Resque
class QuietFormatter
def call(serverity, datetime, progname, msg)
""
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/log_formatters/verbose_formatter.rb | lib/resque/log_formatters/verbose_formatter.rb | module Resque
class VerboseFormatter
def call(serverity, datetime, progname, msg)
"*** #{msg}\n"
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure/redis.rb | lib/resque/failure/redis.rb | module Resque
module Failure
# A Failure backend that stores exceptions in Redis. Very simple but
# works out of the box, along with support in the Resque web app.
class Redis < Base
def data_store
Resque.data_store
end
def self.data_store
Resque.data_store
end
def save
data = {
:failed_at => UTF8Util.clean(Time.now.strftime("%Y/%m/%d %H:%M:%S %Z")),
:payload => payload,
:exception => exception.class.to_s,
:error => UTF8Util.clean(exception.to_s),
:backtrace => filter_backtrace(Array(exception.backtrace)),
:worker => worker.to_s,
:queue => queue
}
data = Resque.encode(data)
data_store.push_to_failed_queue(data)
end
def self.count(queue = nil, class_name = nil)
check_queue(queue)
if class_name
n = 0
each(0, count(queue), queue, class_name) { n += 1 }
n
else
data_store.num_failed
end
end
def self.queues
data_store.failed_queue_names
end
def self.all(offset = 0, limit = 1, queue = nil)
check_queue(queue)
Resque.list_range(:failed, offset, limit)
end
def self.each(offset = 0, limit = self.count, queue = :failed, class_name = nil, order = 'desc')
if class_name
original_limit = limit
limit = count
end
all_items = limit == 1 ? [all(offset,limit,queue)] : Array(all(offset, limit, queue))
reversed = false
if order.eql? 'desc'
all_items.reverse!
reversed = true
end
all_items.each_with_index do |item, i|
if !class_name || (item['payload'] && item['payload']['class'] == class_name && (original_limit -= 1) >= 0)
if reversed
id = (all_items.length - 1) + (offset - i)
else
id = offset + i
end
yield id, item
end
end
end
def self.clear(queue = nil)
check_queue(queue)
data_store.clear_failed_queue
end
def self.requeue(id, queue = nil)
check_queue(queue)
item = all(id)
item['retried_at'] = UTF8Util.clean(Time.now.strftime("%Y/%m/%d %H:%M:%S %Z"))
data_store.update_item_in_failed_queue(id,Resque.encode(item))
Job.create(item['queue'], item['payload']['class'], *item['payload']['args'])
end
def self.remove(id, queue = nil)
check_queue(queue)
data_store.remove_from_failed_queue(id, queue)
end
def self.requeue_queue(queue)
i = 0
while job = all(i)
requeue(i) if job['queue'] == queue
i += 1
end
end
def self.requeue_all
count.times do |num|
requeue(num)
end
end
def self.remove_queue(queue)
i = 0
while job = all(i)
if job['queue'] == queue
# This will remove the failure from the array so do not increment the index.
remove(i)
else
i += 1
end
end
end
def self.check_queue(queue)
raise ArgumentError, "invalid queue: #{queue}" if queue && queue.to_s != "failed"
end
def filter_backtrace(backtrace)
index = backtrace.index { |item| item.include?('/lib/resque/job.rb') }
backtrace.first(index.to_i)
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure/base.rb | lib/resque/failure/base.rb | module Resque
module Failure
# All Failure classes are expected to subclass Base.
#
# When a job fails, a new instance of your Failure backend is created
# and #save is called.
class Base
# The exception object raised by the failed job
attr_accessor :exception
# The worker object who detected the failure
attr_accessor :worker
# The string name of the queue from which the failed job was pulled
attr_accessor :queue
# The payload object associated with the failed job
attr_accessor :payload
def initialize(exception, worker, queue, payload)
@exception = exception
@worker = worker
@queue = queue
@payload = payload
end
# When a job fails, a new instance of your Failure backend is created
# and #save is called.
#
# This is where you POST or PUT or whatever to your Failure service.
def save
end
# The number of failures.
def self.count(queue = nil, class_name = nil)
0
end
# Returns an array of all available failure queues
def self.queues
[]
end
# Returns a paginated array of failure objects.
def self.all(offset = 0, limit = 1, queue = nil)
[]
end
# Iterate across failed objects
def self.each(*args)
end
# A URL where someone can go to view failures.
def self.url
end
# Clear all failure objects
def self.clear(*args)
end
def self.requeue(*args)
end
def self.remove(*args)
end
# Logging!
def log(message)
@worker.log(message)
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure/airbrake.rb | lib/resque/failure/airbrake.rb | begin
require 'airbrake'
rescue LoadError
raise "Can't find 'airbrake' gem. Please add it to your Gemfile or install it."
end
module Resque
module Failure
class Airbrake < Base
def self.configure(&block)
Resque.logger.warn "This actually sets global Airbrake configuration, " \
"which is probably not what you want."
Resque::Failure.backend = self
::Airbrake.configure(&block)
end
def self.count(queue = nil, class_name = nil)
# We can't get the total # of errors from Airbrake so we fake it
# by asking Resque how many errors it has seen.
Stat[:failed]
end
def save
notify(
exception,
parameters: {
payload_class: payload['class'].to_s,
payload_args: payload['args'].inspect
}
)
end
private
def notify(exception, options)
if ::Airbrake.respond_to?(:notify_sync)
::Airbrake.notify_sync(exception, options)
else
# Older versions of Airbrake (< 5)
::Airbrake.notify(exception, options)
end
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure/redis_multi_queue.rb | lib/resque/failure/redis_multi_queue.rb | module Resque
module Failure
# A Failure backend that stores exceptions in Redis. Very simple but
# works out of the box, along with support in the Resque web app.
class RedisMultiQueue < Base
def data_store
Resque.data_store
end
def self.data_store
Resque.data_store
end
def save
data = {
:failed_at => Time.now.strftime("%Y/%m/%d %H:%M:%S %Z"),
:payload => payload,
:exception => exception.class.to_s,
:error => UTF8Util.clean(exception.to_s),
:backtrace => filter_backtrace(Array(exception.backtrace)),
:worker => worker.to_s,
:queue => queue
}
data = Resque.encode(data)
data_store.push_to_failed_queue(data,Resque::Failure.failure_queue_name(queue))
end
def self.count(queue = nil, class_name = nil)
if queue
if class_name
n = 0
each(0, count(queue), queue, class_name) { n += 1 }
n
else
data_store.num_failed(queue).to_i
end
else
total = 0
queues.each { |q| total += count(q) }
total
end
end
def self.all(offset = 0, limit = 1, queue = :failed)
Resque.list_range(queue, offset, limit)
end
def self.queues
data_store.failed_queue_names(:failed_queues)
end
def self.each(offset = 0, limit = self.count, queue = :failed, class_name = nil, order = 'desc')
items = all(offset, limit, queue)
items = [items] unless items.is_a? Array
reversed = false
if order.eql? 'desc'
items.reverse!
reversed = true
end
items.each_with_index do |item, i|
if !class_name || (item['payload'] && item['payload']['class'] == class_name)
id = reversed ? (items.length - 1) + (offset - i) : offset + i
yield id, item
end
end
end
def self.clear(queue = :failed)
queues = queue ? Array(queue) : self.queues
queues.each { |queue| data_store.clear_failed_queue(queue) }
end
def self.requeue(id, queue = :failed)
item = all(id, 1, queue)
item['retried_at'] = Time.now.strftime("%Y/%m/%d %H:%M:%S")
data_store.update_item_in_failed_queue(id,Resque.encode(item),queue)
Job.create(item['queue'], item['payload']['class'], *item['payload']['args'])
end
def self.remove(id, queue = :failed)
data_store.remove_from_failed_queue(id,queue)
end
def self.requeue_queue(queue)
failure_queue = Resque::Failure.failure_queue_name(queue)
each(0, count(failure_queue), failure_queue) { |id, _| requeue(id, failure_queue) }
end
def self.requeue_all
queues.each { |queue| requeue_queue(Resque::Failure.job_queue_name(queue)) }
end
def self.remove_queue(queue)
data_store.remove_failed_queue(Resque::Failure.failure_queue_name(queue))
end
def filter_backtrace(backtrace)
index = backtrace.index { |item| item.include?('/lib/resque/job.rb') }
backtrace.first(index.to_i)
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/resque/failure/multiple.rb | lib/resque/failure/multiple.rb | module Resque
module Failure
# A Failure backend that uses multiple backends
# delegates all queries to the first backend
class Multiple < Base
class << self
attr_accessor :classes
end
def self.configure
yield self
Resque::Failure.backend = self
end
def initialize(*args)
super
@backends = self.class.classes.map {|klass| klass.new(*args)}
end
def save
@backends.each(&:save)
end
# The number of failures.
def self.count(*args)
classes.first.count(*args)
end
# Returns an array of all available failure queues
def self.queues
classes.first.queues
end
# Returns a paginated array of failure objects.
def self.all(*args)
classes.first.all(*args)
end
# Iterate across failed objects
def self.each(*args, &block)
classes.first.each(*args, &block)
end
# A URL where someone can go to view failures.
def self.url
classes.first.url
end
# Clear all failure objects
def self.clear(*args)
classes.first.clear(*args)
end
def self.requeue(*args)
classes.first.requeue(*args)
end
def self.requeue_all
classes.first.requeue_all
end
def self.requeue_queue(queue)
classes.first.requeue_queue(queue)
end
def self.remove(index, queue = nil)
classes.each { |klass| klass.remove(index, queue) }
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
resque/resque | https://github.com/resque/resque/blob/23dcb83aa9dccd1b56b2f8f95f3956deec2252ff/lib/active_job/queue_adapters/resque_adapter.rb | lib/active_job/queue_adapters/resque_adapter.rb | # frozen_string_literal: true
require "active_support/core_ext/enumerable"
require "active_support/core_ext/array/access"
begin
require "resque-scheduler"
rescue LoadError
begin
require "resque_scheduler"
rescue LoadError
false
end
end
module ActiveJob
module QueueAdapters
remove_const(:ResqueAdapter) if defined?(ResqueAdapter)
# = Resque adapter for Active Job
#
# Resque (pronounced like "rescue") is a Redis-backed library for creating
# background jobs, placing those jobs on multiple queues, and processing
# them later.
#
# Read more about Resque {here}[https://github.com/resque/resque].
#
# To use Resque set the queue_adapter config to +:resque+.
#
# Rails.application.config.active_job.queue_adapter = :resque
class ResqueAdapter < ::ActiveJob::QueueAdapters::AbstractAdapter
def enqueue(job) # :nodoc:
JobWrapper.instance_variable_set(:@queue, job.queue_name)
Resque.enqueue_to job.queue_name, JobWrapper, job.serialize
end
def enqueue_at(job, timestamp) # :nodoc:
unless Resque.respond_to?(:enqueue_at_with_queue)
raise NotImplementedError, "To be able to schedule jobs with Resque you need the " \
"resque-scheduler gem. Please add it to your Gemfile and run bundle install"
end
Resque.enqueue_at_with_queue job.queue_name, timestamp, JobWrapper, job.serialize
end
class JobWrapper # :nodoc:
class << self
def perform(job_data)
::ActiveJob::Base.execute job_data
end
end
end
end
end
end
| ruby | MIT | 23dcb83aa9dccd1b56b2f8f95f3956deec2252ff | 2026-01-04T15:38:34.612770Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/features/support/env.rb | features/support/env.rb | # frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
require 'capybara/cucumber'
require 'capybara/spec/test_app'
Capybara.app = TestApp
# These drivers are only used for testing driver switching.
# They don't actually need to process javascript so use RackTest
Capybara.register_driver :javascript_test do |app|
Capybara::RackTest::Driver.new(app)
end
Capybara.javascript_driver = :javascript_test
Capybara.register_driver :named_test do |app|
Capybara::RackTest::Driver.new(app)
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/features/step_definitions/capybara_steps.rb | features/step_definitions/capybara_steps.rb | # frozen_string_literal: true
When(/^I visit the (?:root|home) page$/) do
visit('/')
end
Then(/^I should see "([^"]*)"$/) do |text|
expect(page).to have_content(text)
end
Then(/^Capybara should use the "([^"]*)" driver$/) do |driver|
expect(Capybara.current_driver).to eq(driver.to_sym)
end
When(/^I use a matcher that fails$/) do
expect(page).to have_css('h1#doesnotexist')
rescue StandardError, RSpec::Expectations::ExpectationNotMetError => e
@error_message = e.message
end
Then(/^the failing exception should be nice$/) do
expect(@error_message).to match(/expected to find css "h1#doesnotexist"/)
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/result_spec.rb | spec/result_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Result do
let :string do
Capybara.string <<-STRING
<ul>
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
<li>Delta</li>
</ul>
STRING
end
let :result do
string.all '//li', minimum: 0 # pass minimum: 0 so lazy evaluation doesn't get triggered yet
end
it 'has a length' do
expect(result.length).to eq(4)
end
it 'has a first element' do
result.first.text == 'Alpha'
end
it 'has a last element' do
result.last.text == 'Delta'
end
it 'splats into multiple assignment' do
first, *rest, last = result
expect(first).to have_text 'Alpha'
expect(rest.first).to have_text 'Beta'
expect(rest.last).to have_text 'Gamma'
expect(last).to have_text 'Delta'
end
it 'can supports values_at method' do
expect(result.values_at(0, 2).map(&:text)).to eq(%w[Alpha Gamma])
end
it 'can return an element by its index' do
expect(result.at(1).text).to eq('Beta')
expect(result[2].text).to eq('Gamma')
end
it 'can be mapped' do
expect(result.map(&:text)).to eq(%w[Alpha Beta Gamma Delta])
end
it 'can be selected' do
expect(result.count do |element|
element.text.include? 't'
end).to eq(2)
end
it 'can be reduced' do
expect(result.reduce('') do |memo, element|
memo + element.text[0]
end).to eq('ABGD')
end
it 'can be sampled' do
expect(result).to include(result.sample)
end
it 'can be indexed' do
expect(result.index do |el|
el.text == 'Gamma'
end).to eq(2)
end
def recalc_result
string.all '//li', minimum: 0 # pass minimum: 0 so lazy evaluation doesn't get triggered yet
end
it 'supports all modes of []' do
expect(recalc_result[1].text).to eq 'Beta'
expect(recalc_result[0, 2].map(&:text)).to eq %w[Alpha Beta]
expect(recalc_result[1..3].map(&:text)).to eq %w[Beta Gamma Delta]
expect(recalc_result[-1].text).to eq 'Delta'
expect(recalc_result[-2, 3].map(&:text)).to eq %w[Gamma Delta]
expect(recalc_result[1...3].map(&:text)).to eq %w[Beta Gamma]
expect(recalc_result[1..7].map(&:text)).to eq %w[Beta Gamma Delta]
expect(recalc_result[2...-1].map(&:text)).to eq %w[Gamma]
expect(recalc_result[2..-1].map(&:text)).to eq %w[Gamma Delta] # rubocop:disable Style/SlicingWithRange
expect(recalc_result[2..].map(&:text)).to eq %w[Gamma Delta]
end
it 'supports endless ranges' do
expect(result[2..].map(&:text)).to eq %w[Gamma Delta]
end
it 'supports inclusive positive beginless ranges' do
expect(result[..2].map(&:text)).to eq %w[Alpha Beta Gamma]
end
it 'supports inclusive negative beginless ranges' do
expect(result[..-2].map(&:text)).to eq %w[Alpha Beta Gamma]
expect(result[..-1].map(&:text)).to eq %w[Alpha Beta Gamma Delta]
end
it 'supports exclusive positive beginless ranges' do
expect(result[...2].map(&:text)).to eq %w[Alpha Beta]
end
it 'supports exclusive negative beginless ranges' do
expect(result[...-2].map(&:text)).to eq %w[Alpha Beta]
expect(result[...-1].map(&:text)).to eq %w[Alpha Beta Gamma]
end
it 'works with filter blocks' do
result = string.all('//li') { |node| node.text == 'Alpha' }
expect(result.size).to eq 1
end
# Not a great test but it indirectly tests what is needed
it 'should evaluate filters lazily for idx' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
# Not processed until accessed
expect(result.instance_variable_get(:@result_cache).size).to be 0
# Only one retrieved when needed
result.first
expect(result.instance_variable_get(:@result_cache).size).to be 1
# works for indexed access
result[0]
expect(result.instance_variable_get(:@result_cache).size).to be 1
result[2]
expect(result.instance_variable_get(:@result_cache).size).to be 3
# All cached when converted to array
result.to_a
expect(result.instance_variable_get(:@result_cache).size).to eq 4
end
it 'should evaluate filters lazily for range' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
result[0..1]
expect(result.instance_variable_get(:@result_cache).size).to be 2
expect(result[0..7].size).to eq 4
expect(result.instance_variable_get(:@result_cache).size).to be 4
end
it 'should evaluate filters lazily for idx and length' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
result[1, 2]
expect(result.instance_variable_get(:@result_cache).size).to be 3
expect(result[2, 5].size).to eq 2
expect(result.instance_variable_get(:@result_cache).size).to be 4
end
it 'should only need to evaluate one result for any?' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
result.any?
expect(result.instance_variable_get(:@result_cache).size).to be 1
end
it 'should evaluate all elements when #to_a called' do
# All cached when converted to array
result.to_a
expect(result.instance_variable_get(:@result_cache).size).to eq 4
end
describe '#each' do
it 'lazily evaluates' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
results = []
result.each do |el|
results << el
expect(result.instance_variable_get(:@result_cache).size).to eq results.size
end
expect(results.size).to eq 4
end
context 'without a block' do
it 'returns an iterator' do
expect(result.each).to be_a(Enumerator)
end
it 'lazily evaluates' do
skip 'JRuby has an issue with lazy enumerator evaluation' if jruby_lazy_enumerator_workaround?
result.each.with_index do |_el, idx|
expect(result.instance_variable_get(:@result_cache).size).to eq(idx + 1) # 0 indexing
end
end
end
end
def jruby_lazy_enumerator_workaround?
RUBY_PLATFORM == 'java'
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/css_builder_spec.rb | spec/css_builder_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# rubocop:disable RSpec/InstanceVariable
RSpec.describe Capybara::Selector::CSSBuilder do
let :builder do
described_class.new(@css)
end
context 'add_attribute_conditions' do
it 'adds a single string condition to a single selector' do
@css = 'div'
selector = builder.add_attribute_conditions(random: 'abc')
expect(selector).to eq %(div[random='abc'])
end
it 'adds multiple string conditions to a single selector' do
@css = 'div'
selector = builder.add_attribute_conditions(random: 'abc', other: 'def')
expect(selector).to eq %(div[random='abc'][other='def'])
end
it 'adds a single string condition to a multiple selector' do
@css = 'div, ul'
selector = builder.add_attribute_conditions(random: 'abc')
expect(selector).to eq %(div[random='abc'], ul[random='abc'])
end
it 'adds multiple string conditions to a multiple selector' do
@css = 'div, ul'
selector = builder.add_attribute_conditions(random: 'abc', other: 'def')
expect(selector).to eq %(div[random='abc'][other='def'], ul[random='abc'][other='def'])
end
it 'adds simple regexp conditions to a single selector' do
@css = 'div'
selector = builder.add_attribute_conditions(random: /abc/, other: /def/)
expect(selector).to eq %(div[random*='abc'][other*='def'])
end
it 'adds wildcard regexp conditions to a single selector' do
@css = 'div'
selector = builder.add_attribute_conditions(random: /abc.*def/, other: /def.*ghi/)
expect(selector).to eq %(div[random*='abc'][random*='def'][other*='def'][other*='ghi'])
end
it 'adds alternated regexp conditions to a single selector' do
@css = 'div'
selector = builder.add_attribute_conditions(random: /abc|def/, other: /def|ghi/)
expect(selector).to eq %(div[random*='abc'][other*='def'], div[random*='abc'][other*='ghi'], div[random*='def'][other*='def'], div[random*='def'][other*='ghi'])
end
it 'adds alternated regexp conditions to a multiple selector' do
@css = 'div,ul'
selector = builder.add_attribute_conditions(other: /def.*ghi|jkl/)
expect(selector).to eq %(div[other*='def'][other*='ghi'], div[other*='jkl'], ul[other*='def'][other*='ghi'], ul[other*='jkl'])
end
it "returns original selector when regexp can't be substringed" do
@css = 'div'
selector = builder.add_attribute_conditions(other: /.+/)
expect(selector).to eq 'div'
end
context ':class' do
it 'handles string with CSS .' do
@css = 'a'
selector = builder.add_attribute_conditions(class: 'my_class')
expect(selector).to eq 'a.my_class'
end
it 'handles negated string with CSS .' do
@css = 'a'
selector = builder.add_attribute_conditions(class: '!my_class')
expect(selector).to eq 'a:not(.my_class)'
end
it 'handles array of string with CSS .' do
@css = 'a'
selector = builder.add_attribute_conditions(class: %w[my_class my_other_class])
expect(selector).to eq 'a.my_class.my_other_class'
end
it 'handles array of string with CSS . when negated included' do
@css = 'a'
selector = builder.add_attribute_conditions(class: %w[my_class !my_other_class])
expect(selector).to eq 'a.my_class:not(.my_other_class)'
end
end
context ':id' do
it 'handles string with CSS #' do
@css = 'ul'
selector = builder.add_attribute_conditions(id: 'my_id')
expect(selector).to eq 'ul#my_id'
end
end
end
end
# rubocop:enable RSpec/InstanceVariable
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_edge.rb | spec/selenium_spec_edge.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
# unless ENV['CI']
# Selenium::WebDriver::Edge::Service.driver_path = '/usr/local/bin/msedgedriver'
# end
Selenium::WebDriver.logger.ignore(:selenium_manager)
if Selenium::WebDriver::Platform.mac?
Selenium::WebDriver::Edge.path = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
end
Capybara.register_driver :selenium_edge do |app|
# ::Selenium::WebDriver.logger.level = "debug"
# If we don't create an options object the path set above won't be used
# browser_options = Selenium::WebDriver::Edge::Options.new
# browser_options.add_argument('--headless') if ENV['HEADLESS']
browser_options = if ENV['HEADLESS']
Selenium::WebDriver::Options.edge(args: ['--headless=new'])
else
Selenium::WebDriver::Options.edge
end
Capybara::Selenium::Driver.new(app, browser: :edge, options: browser_options).tap do |driver|
driver.browser
driver.download_path = Capybara.save_path
end
end
module TestSessions
SeleniumEdge = Capybara::Session.new(:selenium_edge, TestApp)
end
skipped_tests = %i[response_headers status_code trigger]
Capybara::SpecHelper.log_selenium_driver_version(Selenium::WebDriver::Edge) if ENV['CI']
Capybara::SpecHelper.run_specs TestSessions::SeleniumEdge, 'selenium', capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when 'Capybara::Session selenium #attach_file with a block can upload by clicking the file input'
pending "Edge doesn't allow clicking on file inputs"
when /Capybara::Session selenium node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
end
end
RSpec.describe 'Capybara::Session with Edge', capybara_skip: skipped_tests do
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::SeleniumEdge, :selenium_edge
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rack_test_spec.rb | spec/rack_test_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module TestSessions
RackTest = Capybara::Session.new(:rack_test, TestApp)
end
skipped_tests = %i[
js
modals
screenshot
frames
windows
send_keys
server
hover
about_scheme
download
css
scroll
spatial
html_validation
shadow_dom
active_element
]
Capybara::SpecHelper.run_specs TestSessions::RackTest, 'RackTest', capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when /has_css\? should support case insensitive :class and :id options/
skip "Nokogiri doesn't support case insensitive CSS attribute matchers"
when /#click_button should follow permanent redirects that maintain method/
skip "Rack < 2 doesn't support 308" if Gem.loaded_specs['rack'].version < Gem::Version.new('2.0.0')
when /#attach_file with multipart form should send prior hidden field if no file submitted/
skip 'Rack-test < 2 needs an empty file to detect multipart form' if Gem.loaded_specs['rack-test'].version < Gem::Version.new('2.0.0')
when /popover/
skip "Rack-test driver doesn't support popover functionality"
end
end
RSpec.describe Capybara::Session do # rubocop:disable RSpec/MultipleDescribes
include Capybara::RSpecMatchers
context 'with rack test driver' do
let(:session) { TestSessions::RackTest }
describe '#driver' do
it 'should be a rack test driver' do
expect(session.driver).to be_an_instance_of(Capybara::RackTest::Driver)
end
end
describe '#mode' do
it 'should remember the mode' do
expect(session.mode).to eq(:rack_test)
end
end
describe '#click_link' do
after do
session.driver.options[:respect_data_method] = false
end
it 'should use data-method if option is true' do
session.driver.options[:respect_data_method] = true
session.visit '/with_html'
session.click_link 'A link with data-method'
expect(session.html).to include('The requested object was deleted')
end
it 'should not use data-method if option is false' do
session.driver.options[:respect_data_method] = false
session.visit '/with_html'
session.click_link 'A link with data-method'
expect(session.html).to include('Not deleted')
end
it "should use data-method if available even if it's capitalized" do
session.driver.options[:respect_data_method] = true
session.visit '/with_html'
session.click_link 'A link with capitalized data-method'
expect(session.html).to include('The requested object was deleted')
end
end
describe '#fill_in' do
it 'should warn that :fill_options are not supported' do
session.visit '/with_html'
expect { session.fill_in 'test_field', with: 'not_monkey', fill_options: { random: true } }.to \
output(/^Options passed to Node#set but the RackTest driver doesn't support any - ignoring/).to_stderr
expect(session).to have_field('test_field', with: 'not_monkey')
end
end
describe '#attach_file' do
context 'with multipart form' do
it 'should submit an empty form-data section if no file is submitted' do
session.visit('/form')
session.click_button('Upload Empty')
expect(session.html).to include('Successfully ignored empty file field.')
end
it 'should submit multipart even if no file is submitted' do
session.visit('/form')
session.click_button('Upload Empty')
expect(session.html).to include('Content type was multipart/form-data;')
end
end
it 'should not submit an obsolete mime type' do
test_jpg_file_path = File.expand_path('fixtures/capybara.csv', File.dirname(__FILE__))
session.visit('/form')
session.attach_file 'form_document', test_jpg_file_path
session.click_button('Upload Single')
expect(session).to have_content('Content-type: text/csv')
end
end
describe '#click' do
context 'on a label' do
it 'should toggle the associated checkbox' do
session.visit('/form')
expect(session).to have_unchecked_field('form_pets_cat')
session.find(:label, 'Cat').click
expect(session).to have_checked_field('form_pets_cat')
session.find(:label, 'Cat').click
expect(session).to have_unchecked_field('form_pets_cat')
session.find(:label, 'McLaren').click
expect(session).to have_checked_field('form_cars_mclaren', visible: :hidden)
end
it 'should toggle the associated radio' do
session.visit('/form')
expect(session).to have_unchecked_field('gender_male')
session.find(:label, 'Male').click
expect(session).to have_checked_field('gender_male')
session.find(:label, 'Female').click
expect(session).to have_unchecked_field('gender_male')
end
it 'should rewrite the forms action query for get submission' do
session.visit('/form')
session.click_button('mediocre')
expect(session).not_to have_current_path(/foo|bar/)
end
it 'should rewrite the submit buttons formaction query for get submission' do
session.visit('/form')
session.click_button('mediocre2')
expect(session).not_to have_current_path(/foo|bar/)
end
end
end
describe '#send_keys' do
it 'raises an UnsupportedMethodError' do
session.visit('/form')
expect { session.send_keys(:tab) }.to raise_error(Capybara::NotSupportedByDriverError)
end
end
describe '#active_element' do
it 'raises an UnsupportedMethodError' do
session.visit('/form')
expect { session.active_element }.to raise_error(Capybara::NotSupportedByDriverError)
end
end
describe '#text' do
it 'should return original text content for textareas' do
session.visit('/with_html')
session.find_field('normal', type: 'textarea', with: 'banana').set('hello')
normal = session.find(:css, '#normal')
expect(normal.value).to eq 'hello'
expect(normal.text).to eq 'banana'
end
end
describe '#style' do
it 'should raise an error' do
session.visit('/with_html')
el = session.find(:css, '#first')
expect { el.style('display') }.to raise_error NotImplementedError, /not process CSS/
end
end
end
end
RSpec.describe Capybara::RackTest::Driver do
let(:driver) { TestSessions::RackTest.driver }
describe ':headers option' do
it 'should always set headers' do
driver = described_class.new(TestApp, headers: { 'HTTP_FOO' => 'foobar' })
driver.visit('/get_header')
expect(driver.html).to include('foobar')
end
it 'should keep headers on link clicks' do
driver = described_class.new(TestApp, headers: { 'HTTP_FOO' => 'foobar' })
driver.visit('/header_links')
driver.find_xpath('.//a').first.click
expect(driver.html).to include('foobar')
end
it 'should keep headers on form submit' do
driver = described_class.new(TestApp, headers: { 'HTTP_FOO' => 'foobar' })
driver.visit('/header_links')
driver.find_xpath('.//input').first.click
expect(driver.html).to include('foobar')
end
it 'should keep headers on redirects' do
driver = described_class.new(TestApp, headers: { 'HTTP_FOO' => 'foobar' })
driver.visit('/get_header_via_redirect')
expect(driver.html).to include('foobar')
end
end
describe ':follow_redirects option' do
it 'defaults to following redirects' do
driver = described_class.new(TestApp)
driver.visit('/redirect')
expect(driver.response.headers['Location']).to be_nil
expect(driver.current_url).to match %r{/landed$}
end
it 'should not include fragments in the referer header' do
driver.visit('/header_links#an-anchor')
driver.find_xpath('.//input').first.click
expect(driver.request.get_header('HTTP_REFERER')).to eq('http://www.example.com/header_links')
end
it 'is possible to not follow redirects' do
driver = described_class.new(TestApp, follow_redirects: false)
driver.visit('/redirect')
expect(driver.response.headers['Location']).to match %r{/redirect_again$}
expect(driver.current_url).to match %r{/redirect$}
end
end
describe ':redirect_limit option' do
context 'with default redirect limit' do
let(:driver) { described_class.new(TestApp) }
it 'should follow 5 redirects' do
driver.visit('/redirect/5/times')
expect(driver.html).to include('redirection complete')
end
it 'should not follow more than 6 redirects' do
expect do
driver.visit('/redirect/6/times')
end.to raise_error(Capybara::InfiniteRedirectError)
end
end
context 'with 21 redirect limit' do
let(:driver) { described_class.new(TestApp, redirect_limit: 21) }
it 'should follow 21 redirects' do
driver.visit('/redirect/21/times')
expect(driver.html).to include('redirection complete')
end
it 'should not follow more than 21 redirects' do
expect do
driver.visit('/redirect/22/times')
end.to raise_error(Capybara::InfiniteRedirectError)
end
end
end
end
RSpec.describe 'Capybara::String' do
it 'should use HTML5 parsing' do
skip 'Only valid if Nokogiri >= 1.12.0 or gumbo is included' unless defined? Nokogiri::HTML5
Capybara.use_html5_parsing = true
allow(Nokogiri::HTML5).to receive(:parse).and_call_original
Capybara.string('<div id=test_div></div>')
expect(Nokogiri::HTML5).to have_received(:parse)
end
end
module CSSHandlerIncludeTester
def dont_extend_css_handler
raise 'should never be called'
end
end
RSpec.describe Capybara::RackTest::CSSHandlers do
include CSSHandlerIncludeTester
it 'should not be extended by global includes' do
expect(described_class.new).not_to respond_to(:dont_extend_css_handler)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/basic_node_spec.rb | spec/basic_node_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara do
include Capybara::RSpecMatchers
describe '.string' do
let :string do
described_class.string <<-STRING
<html>
<head>
<title>simple_node</title>
</head>
<body>
<svg><title>not document title</title></svg>
<div id="page">
<div id="content">
<h1 data="fantastic">Totally awesome</h1>
<p>Yes it is</p>
</div>
<form>
<input type="text" name="bleh" disabled="disabled"/>
<input type="text" name="meh"/>
</form>
<div id="footer">
<p>c2010</p>
<p>Jonas Nicklas</p>
<input type="text" name="foo" value="bar"/>
<select name="animal">
<option>Monkey</option>
<option selected="selected">Capybara</option>
</select>
</div>
<div id="hidden" style="display: none">
<p id="secret">Secret</p>
</div>
<section>
<div class="subsection"></div>
</section>
</div>
</body>
</html>
STRING
end
it 'allows using matchers' do
expect(string).to have_css('#page')
expect(string).not_to have_css('#does-not-exist')
end
it 'allows using custom matchers' do
described_class.add_selector :lifeform do
xpath { |name| ".//option[contains(.,'#{name}')]" }
end
expect(string).to have_selector(:id, 'page')
expect(string).not_to have_selector(:id, 'does-not-exist')
expect(string).to have_selector(:lifeform, 'Monkey')
expect(string).not_to have_selector(:lifeform, 'Gorilla')
end
it 'allows custom matcher using css' do
described_class.add_selector :section do
css { |css_class| "section .#{css_class}" }
end
expect(string).to have_selector(:section, 'subsection')
expect(string).not_to have_selector(:section, 'section_8')
end
it 'allows using matchers with text option' do
expect(string).to have_css('h1', text: 'Totally awesome')
expect(string).not_to have_css('h1', text: 'Not so awesome')
end
it 'allows finding only visible nodes' do
expect(string.all(:css, '#secret', visible: true)).to be_empty
expect(string.all(:css, '#secret', visible: false).size).to eq(1)
end
it 'allows finding elements and extracting text from them' do
expect(string.find('//h1').text).to eq('Totally awesome')
end
it 'allows finding elements and extracting attributes from them' do
expect(string.find('//h1')[:data]).to eq('fantastic')
end
it 'allows finding elements and extracting the tag name from them' do
expect(string.find('//h1').tag_name).to eq('h1')
end
it 'allows finding elements and extracting the path' do
expect(string.find('//h1').path).to eq('/html/body/div/div[1]/h1')
end
it 'allows finding elements and extracting the value' do
expect(string.find('//div/input').value).to eq('bar')
expect(string.find('//select').value).to eq('Capybara')
end
it 'allows finding elements and checking if they are visible' do
expect(string.find('//h1')).to be_visible
expect(string.find(:css, '#secret', visible: false)).not_to be_visible
end
it 'allows finding elements and checking if they are disabled' do
expect(string.find('//form/input[@name="bleh"]')).to be_disabled
expect(string.find('//form/input[@name="meh"]')).not_to be_disabled
end
it 'allows finding siblings' do
h1 = string.find(:css, 'h1')
expect(h1).to have_sibling(:css, 'p', text: 'Yes it is')
expect(h1).not_to have_sibling(:css, 'p', text: 'Jonas Nicklas')
end
it 'allows finding ancestor' do
h1 = string.find(:css, 'h1')
expect(h1).to have_ancestor(:css, '#content')
expect(h1).not_to have_ancestor(:css, '#footer')
end
it 'drops illegal fragments when using gumbo' do
skip 'libxml is less strict than Gumbo' unless Nokogiri.respond_to?(:HTML5)
described_class.use_html5_parsing = true
expect(described_class.string('<td>1</td>')).not_to have_css('td')
end
it 'can disable use of HTML5 parsing' do
skip "Test doesn't make sense unlesss HTML5 parsing is loaded (Nokogumbo or Nokogiri >= 1.12.0)" unless Nokogiri.respond_to?(:HTML5)
described_class.use_html5_parsing = false
expect(described_class.string('<td>1</td>')).to have_css('td')
end
describe '#title' do
it 'returns the page title' do
expect(string.title).to eq('simple_node')
end
end
describe '#has_title?' do
it 'returns whether the page has the given title' do
expect(string.has_title?('simple_node')).to be true
expect(string.has_title?('monkey')).to be false
end
it 'allows regexp matches' do
expect(string.has_title?(/s[a-z]+_node/)).to be true
expect(string.has_title?(/monkey/)).to be false
end
end
describe '#has_no_title?' do
it 'returns whether the page does not have the given title' do
expect(string.has_no_title?('simple_node')).to be false
expect(string.has_no_title?('monkey')).to be true
end
it 'allows regexp matches' do
expect(string.has_no_title?(/s[a-z]+_node/)).to be false
expect(string.has_no_title?(/monkey/)).to be true
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selector_spec.rb | spec/selector_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara do
include Capybara::RSpecMatchers
describe 'Selectors' do
let :string do
described_class.string <<-STRING
<html>
<head>
<title>selectors</title>
</head>
<body>
<div class="aa" id="page">
<div class="bb" id="content">
<h1 class="aa">Totally awesome</h1>
<p>Yes it is</p>
</div>
<p class="bb cc">Some Content</p>
<p class="bb dd !mine"></p>
</div>
<div id="#special">
</div>
<div class="some random words" id="random_words">
Something
</div>
<input id="2checkbox" class="2checkbox" type="checkbox"/>
<input type="radio"/>
<label for="my_text_input">My Text Input</label>
<input type="text" name="form[my_text_input]" placeholder="my text" id="my_text_input"/>
<input type="file" id="file" class=".special file"/>
<input type="hidden" id="hidden_field" value="this is hidden"/>
<input type="submit" value="click me" title="submit button"/>
<input type="button" value="don't click me" title="Other button 1" style="line-height: 30px;"/>
<a href="#">link</a>
<fieldset></fieldset>
<select id="select">
<option value="a">A</option>
<option value="b" disabled>B</option>
<option value="c" selected>C</option>
</select>
<table>
<tr><td></td></tr>
</table>
<table id="rows">
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr>
<td>D</td><td>E</td><td>F</td>
</tr>
</table>
<table id="cols">
<tbody>
<tr>
<td>A</td><td>D</td>
</tr>
<tr>
<td>B</td><td>E</td>
</tr>
<tr>
<td>C</td><td>F</td>
</tr>
</tbody>
</table>
</body>
</html>
STRING
end
before do
described_class.add_selector :custom_selector do
css { |css_class| "div.#{css_class}" }
node_filter(:not_empty, boolean: true, default: true, skip_if: :all) { |node, value| value ^ (node.text == '') }
end
described_class.add_selector :custom_css_selector do
css(:name, :other_name) do |selector, name: nil, **|
selector ||= ''
selector += "[name='#{name}']" if name
selector
end
expression_filter(:placeholder) do |expr, val|
expr + "[placeholder='#{val}']"
end
expression_filter(:value) do |expr, val|
expr + "[value='#{val}']"
end
expression_filter(:title) do |expr, val|
expr + "[title='#{val}']"
end
end
described_class.add_selector :custom_xpath_selector do
xpath(:valid1, :valid2) { |selector| selector }
match { |value| value == 'match_me' }
end
end
it 'supports `filter` as an alias for `node_filter`' do
expect do
described_class.add_selector :filter_alias_selector do
css { |_unused| 'div' }
filter(:something) { |_node, _value| true }
end
end.not_to raise_error
end
describe 'adding a selector' do
it 'can set default visibility' do
described_class.add_selector :hidden_field do
visible :hidden
css { |_sel| 'input[type="hidden"]' }
end
expect(string).to have_no_css('input[type="hidden"]') # rubocop:disable Capybara/SpecificMatcher
expect(string).to have_selector(:hidden_field)
end
end
describe 'modify_selector' do
it 'allows modifying a selector' do
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'div'
described_class.modify_selector :custom_selector do
css { |css_class| "h1.#{css_class}" }
end
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'h1'
end
it "doesn't change existing filters" do
described_class.modify_selector :custom_selector do
css { |css_class| "p.#{css_class}" }
end
expect(string).to have_selector(:custom_selector, 'bb', count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: false, count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: :all, count: 2)
end
end
describe '::[]' do
it 'can find a selector' do
expect(Capybara::Selector[:field]).not_to be_nil
end
it 'raises if no selector found' do
expect { Capybara::Selector[:no_exist] }.to raise_error(ArgumentError, /Unknown selector type/)
end
end
describe '::for' do
it 'finds selector that matches the locator' do
expect(Capybara::Selector.for('match_me').name).to eq :custom_xpath_selector
end
it 'returns nil if no match' do
expect(Capybara::Selector.for('nothing')).to be_nil
end
end
describe 'xpath' do
it 'uses filter names passed in' do
described_class.add_selector :test do
xpath(:something, :other) { |_locator| XPath.descendant }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:something, :other)
end
it 'gets filter names from block if none passed to xpath method' do
described_class.add_selector :test do
xpath { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
xpath(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'css' do
it "supports filters specified in 'css' definition" do
expect(string).to have_selector(:custom_css_selector, 'input', name: 'form[my_text_input]')
expect(string).to have_no_selector(:custom_css_selector, 'input', name: 'form[not_my_text_input]')
end
it 'supports explicitly defined expression filters' do
expect(string).to have_selector(:custom_css_selector, placeholder: 'my text')
expect(string).to have_no_selector(:custom_css_selector, placeholder: 'not my text')
expect(string).to have_selector(:custom_css_selector, value: 'click me', title: 'submit button')
end
it 'uses filter names passed in' do
described_class.add_selector :test do
css(:name, :other_name) { |_locator| '' }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:name, :other_name)
end
it 'gets filter names from block if none passed to css method' do
described_class.add_selector :test do
css { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
css(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'builtin selectors' do
context 'when locator is nil' do
it 'devolves to just finding element types' do
selectors = {
field: ".//*[self::input | self::textarea | self::select][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]",
fieldset: './/fieldset',
link: './/a[./@href]',
link_or_button: ".//a[./@href] | .//input[./@type = 'submit' or ./@type = 'reset' or ./@type = 'image' or ./@type = 'button'] | .//button",
fillable_field: ".//*[self::input | self::textarea][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'radio' or ./@type = 'checkbox' or ./@type = 'hidden' or ./@type = 'file')]",
radio_button: ".//input[./@type = 'radio']",
checkbox: ".//input[./@type = 'checkbox']",
select: './/select',
option: './/option',
file_field: ".//input[./@type = 'file']",
table: './/table'
}
selectors.each do |selector, xpath|
results = string.all(selector, nil).to_a.map(&:native)
expect(results.size).to be > 0
expect(results).to eq string.all(:xpath, xpath).to_a.map(&:native)
end
end
end
context 'with :id option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', id: 'page').size).to eq 1
expect(string.all(:custom_css_selector, 'h1, div', id: 'page').size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'div', id: '#special')[:id]).to eq '#special'
expect(string.find(:custom_css_selector, 'input', id: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: XPath.contains('peci'))[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/input', id: XPath.ends_with('box'))[:id]).to eq '2checkbox'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', id: XPath.contains('peci')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: /peci/)[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/div', id: /pEcI/i)[:id]).to eq '#special'
end
it 'accepts Regexp for css based selectors' do
expect(string.find(:custom_css_selector, 'div', id: /sp.*al/)[:id]).to eq '#special'
end
end
context 'with :class option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', class: 'aa').size).to eq 2
expect(string.all(:custom_css_selector, 'h1, div', class: 'aa').size).to eq 2
end
it 'handles negated classes' do
expect(string.all(:custom_css_selector, 'div, p', class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_css_selector, 'div, p', class: ['!cc', '!dd', 'bb']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!cc', '!dd', 'bb']).size).to eq 1
end
it 'handles classes starting with ! by requiring negated negated first' do
expect(string.all(:custom_css_selector, 'div, p', class: ['!!!mine']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!!!mine']).size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'input', class: '.special')[:id]).to eq 'file'
expect(string.find(:custom_css_selector, 'input', class: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: XPath.contains('dom wor'))[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: XPath.ends_with('words'))[:id]).to eq 'random_words'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', class: XPath.contains('random')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for XPath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: /dom wor/)[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: /dOm WoR/i)[:id]).to eq 'random_words'
end
it 'accepts Regexp for CSS based selectors' do
expect(string.find(:custom_css_selector, 'div', class: /random/)[:id]).to eq 'random_words'
end
it 'accepts Regexp for individual class names for XPath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: [/random/, 'some'])[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: [/om/, /wor/])[:id]).to eq 'random_words'
expect { string.find(:custom_xpath_selector, './/div', class: [/not/, /wor/]) }.to raise_error(Capybara::ElementNotFound)
expect { string.find(:custom_xpath_selector, './/div', class: [/dom wor/]) }.to raise_error(Capybara::ElementNotFound)
end
it 'accepts Regexp for individual class names for CSS based selectors' do
expect(string.find(:custom_css_selector, 'div', class: [/random/])[:id]).to eq 'random_words'
expect(string.find(:custom_css_selector, 'div', class: [/om/, /wor/, 'some'])[:id]).to eq 'random_words'
expect { string.find(:custom_css_selector, 'div', class: [/not/, /wor/]) }.to raise_error(Capybara::ElementNotFound)
expect { string.find(:custom_css_selector, 'div', class: [/dom wor/]) }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :style option' do
it 'accepts string for CSS based selectors' do
expect(string.find(:custom_css_selector, 'input', style: 'line-height: 30px;')[:title]).to eq 'Other button 1'
end
it 'accepts Regexp for CSS base selectors' do
expect(string.find(:custom_css_selector, 'input', style: /30px/)[:title]).to eq 'Other button 1'
end
end
# :css, :xpath, :id, :field, :fieldset, :link, :button, :link_or_button, :fillable_field, :radio_button, :checkbox, :select,
# :option, :file_field, :label, :table, :frame
describe ':css selector' do
it 'finds by CSS locator' do
expect(string.find(:css, 'input#my_text_input')[:name]).to eq 'form[my_text_input]'
end
end
describe ':xpath selector' do
it 'finds by XPath locator' do
expect(string.find(:xpath, './/input[@id="my_text_input"]')[:name]).to eq 'form[my_text_input]'
end
end
describe ':id selector' do
it 'finds by locator' do
expect(string.find(:id, 'my_text_input')[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /my_text_input/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /_text_/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /i[nmo]/)[:name]).to eq 'form[my_text_input]'
end
end
describe ':field selector' do
it 'finds by locator' do
expect(string.find(:field, 'My Text Input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'my_text_input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by id string' do
expect(string.find(:field, id: 'my_text_input')[:name]).to eq 'form[my_text_input]'
end
it 'finds by id regexp' do
expect(string.find(:field, id: /my_text_inp/)[:name]).to eq 'form[my_text_input]'
end
it 'finds by name' do
expect(string.find(:field, name: 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by placeholder' do
expect(string.find(:field, placeholder: 'my text')[:id]).to eq 'my_text_input'
end
it 'finds by type' do
expect(string.find(:field, type: 'file')[:id]).to eq 'file'
expect(string.find(:field, type: 'select')[:id]).to eq 'select'
end
end
describe ':option selector' do
it 'finds disabled options' do
expect(string.find(:option, disabled: true).value).to eq 'b'
end
it 'finds selected options' do
expect(string.find(:option, selected: true).value).to eq 'c'
end
it 'finds not selected and not disabled options' do
expect(string.find(:option, disabled: false, selected: false).value).to eq 'a'
end
end
describe ':button selector' do
it 'finds by value' do
expect(string.find(:button, 'click me').value).to eq 'click me'
end
it 'finds by title' do
expect(string.find(:button, 'submit button').value).to eq 'click me'
end
it 'includes non-matching parameters in failure message' do
expect { string.find(:button, 'click me', title: 'click me') }.to raise_error(/with title click me/)
end
end
describe ':element selector' do
it 'finds by any attributes' do
expect(string.find(:element, 'input', type: 'submit').value).to eq 'click me'
end
it 'supports regexp matching' do
expect(string.find(:element, 'input', type: /sub/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub\w.*button/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.* b.*ton/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.*mit.*/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^submit button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^(?:submit|other) button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /SuB.*mIt/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Su.*Bm.*It/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Ot.*he.*r b.*\d/i).value).to eq "don't click me"
end
it 'still works with system keys' do
expect { string.all(:element, 'input', type: 'submit', count: 1) }.not_to raise_error
end
it 'works without element type' do
expect(string.find(:element, type: 'submit').value).to eq 'click me'
end
it 'validates attribute presence when true' do
expect(string.find(:element, name: true)[:id]).to eq 'my_text_input'
end
it 'validates attribute absence when false' do
expect(string.find(:element, 'option', disabled: false, selected: false).value).to eq 'a'
end
it 'includes wildcarded keys in description' do
expect { string.all(:element, 'input', not_there: 'bad', presence: true, absence: false, count: 1) }
.to(raise_error do |e|
expect(e).to be_a(Capybara::ElementNotFound)
expect(e.message).to include 'not_there => bad'
expect(e.message).to include 'with presence attribute'
expect(e.message).to include 'without absence attribute'
expect(e.message).not_to include 'count 1'
end)
end
it 'accepts XPath::Expression' do
expect(string.find(:element, 'input', type: XPath.starts_with('subm')).value).to eq 'click me'
expect(string.find(:element, 'input', type: XPath.ends_with('ext'))[:type]).to eq 'text'
expect(string.find(:element, 'input', type: XPath.contains('ckb'))[:type]).to eq 'checkbox'
expect(string.find(:element, 'input', title: XPath.contains_word('submit'))[:type]).to eq 'submit'
expect(string.find(:element, 'input', title: XPath.contains_word('button 1'))[:type]).to eq 'button'
end
end
describe ':link_or_button selector' do
around do |example|
described_class.modify_selector(:link_or_button) do
expression_filter(:random) { |xpath, _| xpath } # do nothing filter
end
example.run
Capybara::Selector[:link_or_button].expression_filters.delete(:random)
end
it 'should not find links when disabled == true' do
expect(string.all(:link_or_button, disabled: true).size).to eq 0
end
context 'when modified' do
it 'should still work' do
filter = Capybara::Selector[:link_or_button].expression_filters[:random]
allow(filter).to receive(:apply_filter).and_call_original
expect(string.find(:link_or_button, 'click me', random: 'blah').value).to eq 'click me'
expect(filter).to have_received(:apply_filter).with(anything, :random, 'blah', anything)
end
end
end
describe ':table selector' do
it 'finds by rows' do
expect(string.find(:table, with_rows: [%w[D E F]])[:id]).to eq 'rows'
end
it 'finds by columns' do
expect(string.find(:table, with_cols: [%w[A B C]])[:id]).to eq 'cols'
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/minitest_spec.rb | spec/minitest_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/minitest'
class MinitestTest < Minitest::Test
include Capybara::DSL
include Capybara::Minitest::Assertions
def setup
visit('/form')
end
def teardown
Capybara.reset_sessions!
end
def self.test_order
:sorted
end
def test_assert_text
assert_text('Form', normalize_ws: false)
assert_no_text('Not on the page')
refute_text('Also Not on the page')
end
def test_assert_title
visit('/with_title')
assert_title('Test Title')
assert_no_title('Not the title')
refute_title('Not the title')
end
def test_assert_current_path
assert_current_path('/form')
assert_current_path('/form') { |url| url.query.nil? }
assert_no_current_path('/not_form')
refute_current_path('/not_form')
end
def test_assert_xpath
assert_xpath('.//select[@id="form_title"]')
assert_xpath('.//select', count: 1) { |el| el[:id] == 'form_title' }
assert_no_xpath('.//select[@id="not_form_title"]')
assert_no_xpath('.//select') { |el| el[:id] == 'not_form_title' }
refute_xpath('.//select[@id="not_form_title"]')
end
def test_assert_css
assert_css('select#form_title')
assert_no_css('select#not_form_title')
end
def test_assert_selector
assert_selector(:css, 'select#form_title')
assert_selector(:xpath, './/select[@id="form_title"]')
assert_no_selector(:css, 'select#not_form_title')
assert_no_selector(:xpath, './/select[@id="not_form_title"]')
refute_selector(:css, 'select#not_form_title')
end
def test_assert_element
visit('/with_html')
assert_element('a', text: 'A link')
assert_element(count: 1) { |el| el.text == 'A link' }
assert_no_element(text: 'Not on page')
end
def test_assert_link
visit('/with_html')
assert_link('A link')
assert_link(count: 1) { |el| el.text == 'A link' }
assert_no_link('Not on page')
end
def test_assert_button
assert_button('fresh_btn')
assert_button(count: 1) { |el| el[:id] == 'fresh_btn' }
assert_no_button('not_btn')
end
def test_assert_field
assert_field('customer_email')
assert_no_field('not_on_the_form')
end
def test_assert_select
assert_select('form_title')
assert_no_select('not_form_title')
end
def test_assert_checked_field
assert_checked_field('form_pets_dog')
assert_no_checked_field('form_pets_cat')
refute_checked_field('form_pets_snake')
end
def test_assert_unchecked_field
assert_unchecked_field('form_pets_cat')
assert_no_unchecked_field('form_pets_dog')
refute_unchecked_field('form_pets_snake')
end
def test_assert_table
visit('/tables')
assert_table('agent_table')
assert_no_table('not_on_form')
refute_table('not_on_form')
end
def test_assert_all_of_selectors
assert_all_of_selectors(:css, 'select#form_other_title', 'input#form_last_name')
end
def test_assert_none_of_selectors
assert_none_of_selectors(:css, 'input#not_on_page', 'input#also_not_on_page')
end
def test_assert_any_of_selectors
assert_any_of_selectors(:css, 'input#not_on_page', 'select#form_other_title')
end
def test_assert_matches_selector
assert_matches_selector(find(:field, 'customer_email'), :field, 'customer_email')
assert_not_matches_selector(find(:select, 'form_title'), :field, 'customer_email')
refute_matches_selector(find(:select, 'form_title'), :field, 'customer_email')
end
def test_assert_matches_css
assert_matches_css(find(:select, 'form_title'), 'select#form_title')
refute_matches_css(find(:select, 'form_title'), 'select#form_other_title')
end
def test_assert_matches_xpath
assert_matches_xpath(find(:select, 'form_title'), './/select[@id="form_title"]')
refute_matches_xpath(find(:select, 'form_title'), './/select[@id="form_other_title"]')
end
def test_assert_matches_style
skip "Rack test doesn't support style" if Capybara.current_driver == :rack_test
visit('/with_html')
assert_matches_style(find(:css, '#second'), display: 'inline')
end
def test_assert_ancestor
option = find(:option, 'Finnish')
assert_ancestor(option, :css, '#form_locale')
end
def test_assert_sibling
option = find(:css, '#form_title').find(:option, 'Mrs')
assert_sibling(option, :option, 'Mr')
end
end
RSpec.describe 'capybara/minitest' do
before do
Capybara.current_driver = :rack_test
Capybara.app = TestApp
end
after do
Capybara.use_default_driver
end
it 'should support minitest' do
output = StringIO.new
reporter = Minitest::SummaryReporter.new(output)
reporter.start
MinitestTest.run reporter, {}
reporter.report
expect(output.string).to include('23 runs, 56 assertions, 0 failures, 0 errors, 1 skips')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/session_spec.rb | spec/session_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Session do
describe '#new' do
it 'should raise an error if passed non-existent driver' do
expect do
described_class.new(:quox, TestApp).driver
end.to raise_error(Capybara::DriverNotFoundError)
end
it 'verifies a passed app is a rack app' do
expect do
described_class.new(:unknown, random: 'hash')
end.to raise_error TypeError, 'The second parameter to Session::new should be a rack app if passed.'
end
end
context 'current_driver' do
around do |example|
orig_driver = Capybara.current_driver
example.run
Capybara.current_driver = orig_driver
end
it 'is global when threadsafe false' do
Capybara.threadsafe = false
Capybara.current_driver = :selenium
thread = Thread.new do
Capybara.current_driver = :random
end
thread.join
expect(Capybara.current_driver).to eq :random
end
it 'is thread specific threadsafe true' do
Capybara.threadsafe = true
Capybara.current_driver = :selenium
thread = Thread.new do
Capybara.current_driver = :random
end
thread.join
expect(Capybara.current_driver).to eq :selenium
end
end
context 'session_name' do
around do |example|
orig_name = Capybara.session_name
example.run
Capybara.session_name = orig_name
end
it 'is global when threadsafe false' do
Capybara.threadsafe = false
Capybara.session_name = 'sess1'
thread = Thread.new do
Capybara.session_name = 'sess2'
end
thread.join
expect(Capybara.session_name).to eq 'sess2'
end
it 'is thread specific when threadsafe true' do
Capybara.threadsafe = true
Capybara.session_name = 'sess1'
thread = Thread.new do
Capybara.session_name = 'sess2'
end
thread.join
expect(Capybara.session_name).to eq 'sess1'
end
end
context 'quit' do
it 'will reset the driver' do
session = described_class.new(:rack_test, TestApp)
driver = session.driver
session.quit
expect(session.driver).not_to eql driver
end
it 'resets the document' do
session = described_class.new(:rack_test, TestApp)
document = session.document
session.quit
expect(session.document.base).not_to eql document.base
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/dsl_spec.rb | spec/dsl_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/dsl'
class TestClass
include Capybara::DSL
end
Capybara::SpecHelper.run_specs TestClass.new, 'DSL', capybara_skip: %i[
js modals screenshot frames windows send_keys server hover about_scheme psc download css driver scroll spatial html_validation shadow_dom active_element
] do |example|
case example.metadata[:full_description]
when /has_css\? should support case insensitive :class and :id options/
pending "Nokogiri doesn't support case insensitive CSS attribute matchers"
when /#click_button should follow permanent redirects that maintain method/
pending "Rack < 2 doesn't support 308" if Gem.loaded_specs['rack'].version < Gem::Version.new('2.0.0')
when /#attach_file with multipart form should send prior hidden field if no file submitted/
skip 'Rack-test < 2 needs an empty file to detect multipart form' if Gem.loaded_specs['rack-test'].version < Gem::Version.new('2.0.0')
when /popover/
skip "Rack-test driver doesn't support popover functionality"
end
end
RSpec.describe Capybara::DSL do
before do
Capybara.use_default_driver
end
after do
Capybara.session_name = nil
Capybara.default_driver = nil
Capybara.javascript_driver = nil
Capybara.use_default_driver
Capybara.app = TestApp
end
describe '#default_driver' do
it 'should default to rack_test' do
expect(Capybara.default_driver).to eq(:rack_test)
end
it 'should be changeable' do
Capybara.default_driver = :culerity
expect(Capybara.default_driver).to eq(:culerity)
end
end
describe '#current_driver' do
it 'should default to the default driver' do
expect(Capybara.current_driver).to eq(:rack_test)
Capybara.default_driver = :culerity
expect(Capybara.current_driver).to eq(:culerity)
end
it 'should be changeable' do
Capybara.current_driver = :culerity
expect(Capybara.current_driver).to eq(:culerity)
end
end
describe '#javascript_driver' do
it 'should default to selenium' do
expect(Capybara.javascript_driver).to eq(:selenium)
end
it 'should be changeable' do
Capybara.javascript_driver = :culerity
expect(Capybara.javascript_driver).to eq(:culerity)
end
end
describe '#use_default_driver' do
it 'should restore the default driver' do
Capybara.current_driver = :culerity
Capybara.use_default_driver
expect(Capybara.current_driver).to eq(:rack_test)
end
end
describe '#using_driver' do
before do
expect(Capybara.current_driver).not_to eq(:selenium) # rubocop:disable RSpec/ExpectInHook
end
it 'should set the driver using Capybara.current_driver=' do
driver = nil
Capybara.using_driver(:selenium) { driver = Capybara.current_driver }
expect(driver).to eq(:selenium)
end
it 'should return the driver to default if it has not been changed' do
Capybara.using_driver(:selenium) do
expect(Capybara.current_driver).to eq(:selenium)
end
expect(Capybara.current_driver).to eq(Capybara.default_driver)
end
it 'should reset the driver even if an exception occurs' do
driver_before_block = Capybara.current_driver
begin
Capybara.using_driver(:selenium) { raise 'ohnoes!' }
rescue Exception # rubocop:disable Lint/RescueException,Lint/SuppressedException
end
expect(Capybara.current_driver).to eq(driver_before_block)
end
it 'should return the driver to what it was previously' do
Capybara.current_driver = :selenium
Capybara.using_driver(:culerity) do
Capybara.using_driver(:rack_test) do
expect(Capybara.current_driver).to eq(:rack_test)
end
expect(Capybara.current_driver).to eq(:culerity)
end
expect(Capybara.current_driver).to eq(:selenium)
end
it 'should yield the passed block' do
called = false
Capybara.using_driver(:selenium) { called = true }
expect(called).to be(true)
end
end
# rubocop:disable RSpec/InstanceVariable
describe '#using_wait_time' do
before { @previous_wait_time = Capybara.default_max_wait_time }
after { Capybara.default_max_wait_time = @previous_wait_time }
it 'should switch the wait time and switch it back' do
in_block = nil
Capybara.using_wait_time 6 do
in_block = Capybara.default_max_wait_time
end
expect(in_block).to eq(6)
expect(Capybara.default_max_wait_time).to eq(@previous_wait_time)
end
it 'should ensure wait time is reset' do
expect do
Capybara.using_wait_time 6 do
raise 'hell'
end
end.to raise_error(RuntimeError, 'hell')
expect(Capybara.default_max_wait_time).to eq(@previous_wait_time)
end
end
# rubocop:enable RSpec/InstanceVariable
describe '#app' do
it 'should be changeable' do
Capybara.app = 'foobar'
expect(Capybara.app).to eq('foobar')
end
end
describe '#current_session' do
it 'should choose a session object of the current driver type' do
expect(Capybara.current_session).to be_a(Capybara::Session)
end
it 'should use #app as the application' do
Capybara.app = proc {}
expect(Capybara.current_session.app).to eq(Capybara.app)
end
it 'should change with the current driver' do
expect(Capybara.current_session.mode).to eq(:rack_test)
Capybara.current_driver = :selenium
expect(Capybara.current_session.mode).to eq(:selenium)
end
it 'should be persistent even across driver changes' do
object_id = Capybara.current_session.object_id
expect(Capybara.current_session.object_id).to eq(object_id)
Capybara.current_driver = :selenium
expect(Capybara.current_session.mode).to eq(:selenium)
expect(Capybara.current_session.object_id).not_to eq(object_id)
Capybara.current_driver = :rack_test
expect(Capybara.current_session.object_id).to eq(object_id)
end
it 'should change when changing application' do
object_id = Capybara.current_session.object_id
expect(Capybara.current_session.object_id).to eq(object_id)
Capybara.app = proc {}
expect(Capybara.current_session.object_id).not_to eq(object_id)
expect(Capybara.current_session.app).to eq(Capybara.app)
end
it 'should change when the session name changes' do
object_id = Capybara.current_session.object_id
Capybara.session_name = :administrator
expect(Capybara.session_name).to eq(:administrator)
expect(Capybara.current_session.object_id).not_to eq(object_id)
Capybara.session_name = :default
expect(Capybara.session_name).to eq(:default)
expect(Capybara.current_session.object_id).to eq(object_id)
end
end
describe '#using_session' do
it 'should change the session name for the duration of the block' do
expect(Capybara.session_name).to eq(:default)
Capybara.using_session(:administrator) do
expect(Capybara.session_name).to eq(:administrator)
end
expect(Capybara.session_name).to eq(:default)
end
it 'should reset the session to the default, even if an exception occurs' do
begin
Capybara.using_session(:raise) do
raise
end
rescue Exception # rubocop:disable Lint/RescueException,Lint/SuppressedException
end
expect(Capybara.session_name).to eq(:default)
end
it 'should yield the passed block' do
called = false
Capybara.using_session(:administrator) { called = true }
expect(called).to be(true)
end
it 'should be nestable' do
Capybara.using_session(:outer) do
expect(Capybara.session_name).to eq(:outer)
Capybara.using_session(:inner) do
expect(Capybara.session_name).to eq(:inner)
end
expect(Capybara.session_name).to eq(:outer)
end
expect(Capybara.session_name).to eq(:default)
end
it 'should allow a session object' do
original_session = Capybara.current_session
new_session = Capybara::Session.new(:rack_test, proc {})
Capybara.using_session(new_session) do
expect(Capybara.current_session).to eq(new_session)
end
expect(Capybara.current_session).to eq(original_session)
end
it 'should pass the new session if block accepts' do
original_session = Capybara.current_session
Capybara.using_session(:administrator) do |admin_session, prev_session|
expect(admin_session).to be(Capybara.current_session)
expect(prev_session).to be(original_session)
expect(prev_session).not_to be(admin_session)
end
end
end
describe '#session_name' do
it 'should default to :default' do
expect(Capybara.session_name).to eq(:default)
end
end
describe 'the DSL' do
let(:session) { Class.new { include Capybara::DSL }.new }
it 'should be possible to include it in another class' do
session.visit('/with_html')
session.click_link('ullamco')
expect(session.body).to include('Another World')
end
it "should provide a 'page' shortcut for more expressive tests" do
session.page.visit('/with_html')
session.page.click_link('ullamco')
expect(session.page.body).to include('Another World')
end
it "should provide an 'using_session' shortcut" do
allow(Capybara).to receive(:using_session)
session.using_session(:name)
expect(Capybara).to have_received(:using_session).with(:name)
end
it "should provide a 'using_wait_time' shortcut" do
allow(Capybara).to receive(:using_wait_time)
session.using_wait_time(6)
expect(Capybara).to have_received(:using_wait_time).with(6)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec_matchers_spec.rb | spec/rspec_matchers_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Capybara RSpec Matchers', type: :feature do
context 'after called on session' do
it 'HaveSelector should allow getting a description of the matcher' do
visit('/with_html')
matcher = have_selector(:css, 'h2.head', minimum: 3)
expect(page).to matcher
expect { matcher.description }.not_to raise_error
end
it 'HaveText should allow getting a description' do
visit('/with_html')
matcher = have_text('Lorem')
expect(page).to matcher
expect { matcher.description }.not_to raise_error
end
it 'should produce the same error for .to have_no_xxx and .not_to have_xxx' do
visit('/with_html')
not_to_msg = error_msg_for { expect(page).not_to have_selector(:css, '#referrer') }
have_no_msg = error_msg_for { expect(page).to have_no_selector(:css, '#referrer') }
expect(not_to_msg).to eq have_no_msg
not_to_msg = error_msg_for { expect(page).not_to have_text('This is a test') }
have_no_msg = error_msg_for { expect(page).to have_no_text('This is a test') }
expect(not_to_msg).to eq have_no_msg
end
end
context 'after called on element' do
it 'HaveSelector should allow getting a description' do
visit('/with_html')
el = find(:css, '#first')
matcher = have_selector(:css, 'a#foo')
expect(el).to matcher
expect { matcher.description }.not_to raise_error
end
it 'MatchSelector should allow getting a description' do
visit('/with_html')
el = find(:css, '#first')
matcher = match_selector(:css, '#first')
expect(el).to matcher
expect { matcher.description }.not_to raise_error
end
it 'HaveText should allow getting a description' do
visit('/with_html')
el = find(:css, '#first')
matcher = have_text('Lorem')
expect(el).to matcher
expect { matcher.description }.not_to raise_error
end
end
context 'with a filter block' do
it 'applies the filter' do
visit('/with_html')
expect(page).to have_selector(:css, 'input#test_field')
expect(page).to have_selector(:css, 'input', count: 1) { |input| input.value == 'monkey' }
expect(page).to have_selector(:css, 'input', count: 1) do |input|
input.value == 'monkey'
end
expect(page).to have_no_selector(:css, 'input#test_field') { |input| input.value == 'not a monkey' }
expect(page).to have_no_selector(:css, 'input#test_field') do |input|
input.value == 'not a monkey'
end
expect(page).not_to have_selector(:css, 'input#test_field') { |input| input.value == 'not a monkey' }
expect(page).not_to have_selector(:css, 'input#test_field') do |input|
input.value == 'not a monkey'
end
expect(page).not_to have_no_selector(:css, 'input', count: 1) { |input| input.value == 'monkey' }
expect(page).not_to have_no_selector(:css, 'input#test_field', count: 1) do |input|
input.value == 'monkey'
end
end
end
def error_msg_for(&block)
expect(&block).to(raise_error { |e| return e.message })
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec_spec.rb | spec/rspec_spec.rb | # frozen_string_literal: true
# rubocop:disable RSpec/MultipleDescribes
require 'spec_helper'
RSpec.describe 'capybara/rspec' do
context 'Feature', type: :feature do
it 'should include Capybara in rspec' do
visit('/foo')
expect(page.body).to include('Another World')
end
it 'should include RSpec matcher proxies' do
expect(self.class.ancestors).to include Capybara::RSpecMatcherProxies
end
context 'resetting session', order: :defined do
it 'sets a cookie in one example...' do
visit('/set_cookie')
expect(page.body).to include('Cookie set to test_cookie')
end
it '...then it is not available in the next' do
visit('/get_cookie')
expect(page.body).not_to include('test_cookie')
end
end
context 'setting the current driver', order: :defined do
it 'sets the current driver in one example...' do
Capybara.current_driver = :selenium
end
it '...then it has returned to the default in the next example' do
expect(Capybara.current_driver).to eq(:rack_test)
end
end
it 'switches to the javascript driver when giving it as metadata', :js do
expect(Capybara.current_driver).to eq(Capybara.javascript_driver)
end
it 'switches to the given driver when giving it as metadata', driver: :culerity do
expect(Capybara.current_driver).to eq(:culerity)
end
describe '#all' do
it 'allows access to the Capybara finder' do
visit('/with_html')
found = all(:css, 'h2') { |element| element[:class] == 'head' }
expect(found.size).to eq(5)
end
it 'allows access to the RSpec matcher' do
visit('/with_html')
strings = %w[test1 test2]
expect(strings).to all(be_a(String))
end
end
describe '#within' do
it 'allows access to the Capybara scoper' do
visit('/with_html')
expect do
within(:css, '#does_not_exist') { click_link 'Go to simple' }
end.to raise_error(Capybara::ElementNotFound)
end
it 'allows access to the RSpec matcher' do
visit('/with_html')
# This reads terribly, but must call #within
expect(find(:css, 'span.number').text.to_i).to within(1).of(41)
end
end
end
context 'Type: Other', type: :other do
context 'when RSpec::Matchers is included after Capybara::DSL' do
let(:test_class_instance) do
Class.new do
include Capybara::DSL
include RSpec::Matchers
end.new
end
describe '#all' do
it 'allows access to the Capybara finder' do
test_class_instance.visit('/with_html')
expect(test_class_instance.all(:css, 'h2.head').size).to eq(5)
end
it 'allows access to the RSpec matcher' do
test_class_instance.visit('/with_html')
strings = %w[test1 test2]
expect(strings).to test_class_instance.all(be_a(String))
end
end
describe '#within' do
it 'allows access to the Capybara scoper' do
test_class_instance.visit('/with_html')
expect do
test_class_instance.within(:css, '#does_not_exist') { test_class_instance.click_link 'Go to simple' }
end.to raise_error(Capybara::ElementNotFound)
end
it 'allows access to the RSpec matcher' do
test_class_instance.visit('/with_html')
# This reads terribly, but must call #within
expect(test_class_instance.find(:css, 'span.number').text.to_i).to test_class_instance.within(1).of(41)
end
end
context 'when `match_when_negated` is not defined in a matcher' do
before do
RSpec::Matchers.define :only_match_matcher do |expected|
match do |actual|
!(actual ^ expected)
end
end
end
it 'can be called with `not_to`' do
# This test is for a bug in jruby where `super` isn't defined correctly - https://github.com/jruby/jruby/issues/4678
# Reported in https://github.com/teamcapybara/capybara/issues/2115
test_class_instance.instance_eval do
expect do
expect(true).not_to only_match_matcher(false) # rubocop:disable RSpec/ExpectActual
end.not_to raise_error
end
end
end
end
it 'should not include Capybara' do
expect { visit('/') }.to raise_error(NoMethodError)
end
end
end
feature 'Feature DSL' do
scenario 'is pulled in' do
visit('/foo')
expect(page.body).to include('Another World')
end
end
# rubocop:enable RSpec/MultipleDescribes
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/sauce_spec_chrome.rb | spec/sauce_spec_chrome.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'sauce_whisk'
# require 'shared_selenium_session'
# require 'shared_selenium_node'
# require 'rspec/shared_spec_matchers'
Capybara.register_driver :sauce_chrome do |app|
options = {
selenium_version: '4.8.0',
platform: 'macOS 10.12',
browser_name: 'chrome',
version: '65.0',
name: 'Capybara test',
build: ENV.fetch('TRAVIS_REPO_SLUG', "Ruby-RSpec-Selenium: Local-#{Time.now.to_i}"),
username: ENV.fetch('SAUCE_USERNAME', nil),
access_key: ENV.fetch('SAUCE_ACCESS_KEY', nil)
}
options.delete(:browser_name)
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(options)
url = 'https://ondemand.saucelabs.com:443/wd/hub'
Capybara::Selenium::Driver.new(app,
browser: :remote, url: url,
capabilities: capabilities,
options: Selenium::WebDriver::Chrome::Options.new(args: ['']))
end
CHROME_REMOTE_DRIVER = :sauce_chrome
module TestSessions
Chrome = Capybara::Session.new(CHROME_REMOTE_DRIVER, TestApp)
end
skipped_tests = %i[response_headers status_code trigger download]
Capybara::SpecHelper.run_specs TestSessions::Chrome, CHROME_REMOTE_DRIVER.to_s, capybara_skip: skipped_tests do |example|
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_chrome.rb | spec/selenium_spec_chrome.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
CHROME_DRIVER = :selenium_chrome
Selenium::WebDriver::Chrome.path = '/usr/bin/google-chrome-beta' if ENV.fetch('CI', nil) && ENV.fetch('CHROME_BETA', nil)
Selenium::WebDriver.logger.ignore(:selenium_manager)
browser_options = if ENV['HEADLESS']
Selenium::WebDriver::Options.chrome(args: ['--headless=new'])
else
Selenium::WebDriver::Options.chrome
end
# Chromedriver 77 requires setting this for headless mode on linux
# Different versions of Chrome/selenium-webdriver require setting differently - jus set them all
browser_options.add_preference('download.default_directory', Capybara.save_path)
browser_options.add_preference(:download, default_directory: Capybara.save_path)
Capybara.register_driver :selenium_chrome do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
driver_options = { browser: :chrome, timeout: 30 }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **driver_options).tap do |driver|
# Set download dir for Chrome < 77
driver.browser.download_path = Capybara.save_path
end
end
Capybara.register_driver :selenium_chrome_not_clear_storage do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
chrome_options = { browser: :chrome, clear_local_storage: false, clear_session_storage: false }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **chrome_options)
end
Capybara.register_driver :selenium_chrome_not_clear_session_storage do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
chrome_options = { browser: :chrome, clear_session_storage: false }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **chrome_options)
end
Capybara.register_driver :selenium_chrome_not_clear_local_storage do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
chrome_options = { browser: :chrome, clear_local_storage: false }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **chrome_options)
end
Capybara.register_driver :selenium_driver_subclass_with_chrome do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
subclass = Class.new(Capybara::Selenium::Driver)
chrome_options = { browser: :chrome, timeout: 30 }.tap do |opts|
opts[options_key] = browser_options
end
subclass.new(app, **chrome_options)
end
module TestSessions
Chrome = Capybara::Session.new(CHROME_DRIVER, TestApp)
end
skipped_tests = %i[response_headers status_code trigger]
Capybara::SpecHelper.log_selenium_driver_version(Selenium::WebDriver::Chrome) if ENV['CI']
Capybara::SpecHelper.run_specs TestSessions::Chrome, CHROME_DRIVER.to_s, capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when /#click_link can download a file$/
skip 'Need to figure out testing of file downloading on windows platform' if Gem.win_platform?
when /Capybara::Session selenium_chrome node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
when /Capybara::Session selenium_chrome node #shadow_root/
skip 'Not supported with this chromedriver version' if chromedriver_lt?('96.0', @session)
end
end
RSpec.describe 'Capybara::Session with chrome' do
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::Chrome, CHROME_DRIVER
end
context 'storage' do
describe '#reset!' do
it 'clears storage by default' do
session = TestSessions::Chrome
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).to be_empty
end
it 'does not clear storage when false' do
session = Capybara::Session.new(:selenium_chrome_not_clear_storage, TestApp)
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).not_to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).not_to be_empty
end
it 'can not clear session storage' do
session = Capybara::Session.new(:selenium_chrome_not_clear_session_storage, TestApp)
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).not_to be_empty
end
it 'can not clear local storage' do
session = Capybara::Session.new(:selenium_chrome_not_clear_local_storage, TestApp)
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).not_to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).to be_empty
end
end
end
context 'timeout' do
it 'sets the http client read timeout' do
expect(TestSessions::Chrome.driver.browser.send(:bridge).http.read_timeout).to eq 30
end
end
describe 'filling in Chrome-specific date and time fields with keystrokes' do
let(:datetime) { Time.new(1983, 6, 19, 6, 30) }
let(:session) { TestSessions::Chrome }
before do
session.visit('/form')
end
it 'should fill in a date input with a String' do
session.fill_in('form_date', with: '06/19/1983')
session.click_button('awesome')
expect(Date.parse(extract_results(session)['date'])).to eq datetime.to_date
end
it 'should fill in a time input with a String' do
session.fill_in('form_time', with: '06:30A')
session.click_button('awesome')
results = extract_results(session)['time']
expect(Time.parse(results).strftime('%r')).to eq datetime.strftime('%r')
end
it 'should fill in a datetime input with a String' do
session.fill_in('form_datetime', with: "06/19/1983\t06:30A")
session.click_button('awesome')
expect(Time.parse(extract_results(session)['datetime'])).to eq datetime
end
end
describe 'using subclass of selenium driver' do
it 'works' do
session = Capybara::Session.new(:selenium_driver_subclass_with_chrome, TestApp)
session.visit('/form')
expect(session).to have_current_path('/form')
end
end
describe 'log access' do
let(:logs) do
session.driver.browser.then do |chrome_driver|
chrome_driver.respond_to?(:logs) ? chrome_driver : chrome_driver.manage
end.logs
end
it 'does not error getting log types' do
expect do
logs.available_types
end.not_to raise_error
end
it 'does not error when getting logs' do
expect do
logs.get(:browser)
end.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/per_session_config_spec.rb | spec/per_session_config_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/dsl'
RSpec.describe Capybara::SessionConfig do
describe 'threadsafe' do
it 'defaults to global session options' do
Capybara.threadsafe = true
session = Capybara::Session.new(:rack_test, TestApp)
%i[default_host app_host always_include_port run_server
default_selector default_max_wait_time ignore_hidden_elements
automatic_reload match exact raise_server_errors visible_text_only
automatic_label_click enable_aria_label save_path
asset_host default_retry_interval].each do |m|
expect(session.config.public_send(m)).to eq Capybara.public_send(m)
end
end
it "doesn't change global session when changed" do
Capybara.threadsafe = true
host = 'http://my.example.com'
session = Capybara::Session.new(:rack_test, TestApp) do |config|
config.default_host = host
config.automatic_label_click = !config.automatic_label_click
config.server_errors << ArgumentError
end
expect(Capybara.default_host).not_to eq host
expect(session.config.default_host).to eq host
expect(Capybara.automatic_label_click).not_to eq session.config.automatic_label_click
expect(Capybara.server_errors).not_to eq session.config.server_errors
end
it "doesn't allow session configuration block when false" do
Capybara.threadsafe = false
expect do
Capybara::Session.new(:rack_test, TestApp) { |config| }
end.to raise_error 'A configuration block is only accepted when Capybara.threadsafe == true'
end
it "doesn't allow session config when false" do
Capybara.threadsafe = false
session = Capybara::Session.new(:rack_test, TestApp)
expect { session.config.default_selector = :title }.to raise_error(/Per session settings are only supported when Capybara.threadsafe == true/)
expect do
session.configure do |config|
config.exact = true
end
end.to raise_error(/Session configuration is only supported when Capybara.threadsafe == true/)
end
it 'uses the config from the session' do
Capybara.threadsafe = true
session = Capybara::Session.new(:rack_test, TestApp) do |config|
config.default_selector = :link
end
session.visit('/with_html')
expect(session.find('foo').tag_name).to eq 'a'
end
it "won't change threadsafe once a session is created" do
Capybara.threadsafe = true
Capybara.threadsafe = false
Capybara::Session.new(:rack_test, TestApp)
expect { Capybara.threadsafe = true }.to raise_error(/Threadsafe setting cannot be changed once a session is created/)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/capybara_spec.rb | spec/capybara_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara do
describe 'default_max_wait_time' do
before { @previous_default_time = described_class.default_max_wait_time }
after { described_class.default_max_wait_time = @previous_default_time } # rubocop:disable RSpec/InstanceVariable
it 'should be changeable' do
expect(described_class.default_max_wait_time).not_to eq(5)
described_class.default_max_wait_time = 5
expect(described_class.default_max_wait_time).to eq(5)
end
end
describe 'default_retry_interval' do
before { @previous_default_interval = described_class.default_retry_interval }
after { described_class.default_retry_interval = @previous_default_interval } # rubocop:disable RSpec/InstanceVariable
it 'should be changeable' do
expect(described_class.default_retry_interval).not_to eq(0.1)
described_class.default_retry_interval = 0.1
expect(described_class.default_retry_interval).to eq(0.1)
end
end
describe '.register_driver' do
it 'should add a new driver' do
described_class.register_driver :schmoo do |app|
Capybara::RackTest::Driver.new(app)
end
session = Capybara::Session.new(:schmoo, TestApp)
session.visit('/')
expect(session.body).to include('Hello world!')
end
end
describe '.register_server' do
it 'should add a new server' do
described_class.register_server :blob do |_app, _port, _host|
# do nothing
end
expect(described_class.servers[:blob]).to be_truthy
end
end
describe '.server' do
after do
described_class.server = :default
end
it 'should default to a proc that calls run_default_server' do
mock_app = Object.new
allow(described_class).to receive(:run_default_server).and_return(true)
described_class.server.call(mock_app, 8000)
expect(described_class).to have_received(:run_default_server).with(mock_app, 8000)
end
it 'should return a custom server proc' do
server = ->(_app, _port) {}
described_class.register_server :custom, &server
described_class.server = :custom
expect(described_class.server).to eq(server)
end
it 'should have :webrick registered' do
expect(described_class.servers[:webrick]).not_to be_nil
end
it 'should have :puma registered' do
expect(described_class.servers[:puma]).not_to be_nil
end
end
describe 'server=' do
after do
described_class.server = :default
end
it 'accepts a proc' do
server = ->(_app, _port) {}
described_class.server = server
expect(described_class.server).to eq server
end
end
describe 'app_host' do
after do
described_class.app_host = nil
end
it 'should warn if not a valid URL' do
expect { described_class.app_host = 'www.example.com' }.to raise_error(ArgumentError, /Capybara\.app_host should be set to a url/)
end
it 'should not warn if a valid URL' do
expect { described_class.app_host = 'http://www.example.com' }.not_to raise_error
end
it 'should not warn if nil' do
expect { described_class.app_host = nil }.not_to raise_error
end
end
describe 'default_host' do
around do |test|
old_default = described_class.default_host
test.run
described_class.default_host = old_default
end
it 'should raise if not a valid URL' do
expect { described_class.default_host = 'www.example.com' }.to raise_error(ArgumentError, /Capybara\.default_host should be set to a url/)
end
it 'should not warn if a valid URL' do
expect { described_class.default_host = 'http://www.example.com' }.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/regexp_dissassembler_spec.rb | spec/regexp_dissassembler_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Selector::RegexpDisassembler, :aggregate_failures do
it 'handles strings' do
verify_strings(
/abcdef/ => %w[abcdef],
/abc def/ => ['abc def']
)
end
it 'handles escaped characters' do
verify_strings(
/abc\\def/ => %w[abc\def],
/abc\.def/ => %w[abc.def],
/\nabc/ => ["\nabc"],
%r{abc/} => %w[abc/],
/ab\++cd/ => %w[ab+ cd]
)
end
it 'handles wildcards' do
verify_strings(
/abc.*def/ => %w[abc def],
/.*def/ => %w[def],
/abc./ => %w[abc],
/abc.*/ => %w[abc],
/abc.def/ => %w[abc def],
/abc.def.ghi/ => %w[abc def ghi],
/abc.abcd.abcde/ => %w[abcde],
/.*/ => []
)
end
it 'ignores optional characters for substrings' do
{
/abc*def/ => %w[ab def],
/abc*/ => %w[ab],
/c*/ => [],
/abc?def/ => %w[ab def],
/abc?/ => %w[ab],
/abc?def?/ => %w[ab de],
/abc?def?g/ => %w[ab de g],
/d?/ => []
}.each do |regexp, expected|
expect(described_class.new(regexp).substrings).to eq expected
end
end
it 'handles optional characters for #alternated_substrings' do
verify_alternated_strings(
{
/abc*def/ => [%w[ab def]],
/abc*/ => [%w[ab]],
/c*/ => [],
/abc?def/ => [%w[abdef], %w[abcdef]],
/abc?/ => [%w[ab]],
/abc?def?/ => [%w[abde], %w[abcde]],
/abc?def?g/ => [%w[abdeg], %w[abdefg], %w[abcdeg], %w[abcdefg]],
/d?/ => []
}
)
end
it 'handles character classes' do
verify_strings(
/abc[a-z]/ => %w[abc],
/abc[a-z]def[0-9]g/ => %w[abc def g],
/[0-9]abc/ => %w[abc],
/[0-9]+/ => [],
/abc[0-9&&[^7]]/ => %w[abc]
)
end
it 'handles posix bracket expressions' do
verify_strings(
/abc[[:alpha:]]/ => %w[abc],
/[[:digit:]]abc/ => %w[abc],
/abc[[:print:]]def/ => %w[abc def]
)
end
it 'handles repitition' do
verify_strings(
/abc{3}/ => %w[abccc],
/abc{3}d/ => %w[abcccd],
/abc{0}/ => %w[ab],
/abc{,2}/ => %w[ab],
/abc{2,}/ => %w[abcc],
/def{1,5}/ => %w[def],
/abc+def/ => %w[abc def],
/ab(cde){,4}/ => %w[ab],
/(ab){,2}cd/ => %w[cd],
/(abc){2,3}/ => %w[abcabc],
/(abc){3}/ => %w[abcabcabc],
/ab{2,3}cd/ => %w[abb cd],
/(ab){2,3}cd/ => %w[abab cd]
)
end
it 'handles non-greedy repetition' do
verify_strings(
/abc.*?/ => %w[abc],
/abc+?/ => %w[abc],
/abc*?cde/ => %w[ab cde],
/(abc)+?def/ => %w[abc def],
/ab(cde)*?fg/ => %w[ab fg]
)
end
it 'ignores alternation for #substrings' do
{
/abc|def/ => [],
/ab(?:c|d)/ => %w[ab],
/ab(c|d|e)fg/ => %w[ab fg],
/ab?(c|d)fg/ => %w[a fg],
/ab(c|d)ef/ => %w[ab ef],
/ab(cd?|ef)g/ => %w[ab g],
/ab(cd|ef*)g/ => %w[ab g],
/ab|cd*/ => [],
/cd(?:ef|gh)|xyz/ => [],
/(cd(?:ef|gh)|xyz)/ => [],
/cd(ef|gh)+/ => %w[cd],
/cd(ef|gh)?/ => %w[cd],
/cd(ef|gh)?ij/ => %w[cd ij],
/cd(ef|gh)+ij/ => %w[cd ij],
/cd(ef|gh){2}ij/ => %w[cd ij],
/(cd(ef|g*))/ => %w[cd],
/ab(cd){0,2}ef/ => %w[ab ef],
/ab(cd){0,1}ef/ => %w[ab ef],
/ab(cd|cd)ef/ => %w[ab ef],
/ab(cd|cd)?ef/ => %w[ab ef],
/ab\\?cd/ => %w[ab cd]
}.each do |regexp, expected|
expect(described_class.new(regexp).substrings).to eq expected
end
end
it 'handles alternation for #alternated_substrings' do
verify_alternated_strings(
{
/abc|def/ => [%w[abc], %w[def]],
/ab(?:c|d)/ => [%w[abc], %w[abd]],
/ab(c|d|e)fg/ => [%w[abcfg], %w[abdfg], %w[abefg]],
/ab?(c|d)fg/ => [%w[acfg], %w[adfg], %w[abcfg], %w[abdfg]],
/ab(c|d)ef/ => [%w[abcef], %w[abdef]],
/ab(cd?|ef)g/ => [%w[abcg], %w[abcdg], %w[abefg]],
/ab(cd|ef*)g/ => [%w[abcdg], %w[abe g]],
/ab|cd*/ => [%w[ab], %w[c]],
/cd(?:ef|gh)|xyz/ => [%w[cdef], %w[cdgh], %w[xyz]],
/(cd(?:ef|gh)|xyz)/ => [%w[cdef], %w[cdgh], %w[xyz]],
/cd(ef|gh)+/ => [%w[cdef], %w[cdgh]],
/cd(ef|gh)?/ => [%w[cd]],
/cd(ef|gh)?ij/ => [%w[cdij], %w[cdefij], %w[cdghij]],
/cd(ef|gh)+ij/ => [%w[cdef ij], %w[cdgh ij]],
/cd(ef|gh){2}ij/ => [%w[cdefefij], %w[cdefghij], %w[cdghefij], %w[cdghghij]],
/(cd(ef|g*))/ => [%w[cd]],
/a|b*/ => [],
/ab(?:c|d?)/ => [%w[ab]],
/ab(c|d)|a*/ => [],
/(abc)?(d|e)/ => [%w[d], %w[e]],
/(abc*de)?(d|e)/ => [%w[d], %w[e]],
/(abc*de)?(d|e?)/ => [],
/(abc)?(d|e?)/ => [],
/ab(cd){0,2}ef/ => [%w[ab ef]],
/ab(cd){0,1}ef/ => [%w[abef], %w[abcdef]],
/ab(cd|cd)ef/ => [%w[abcdef]],
/ab(cd|cd)?ef/ => [%w[abef], %w[abcdef]],
/ab\\?cd/ => [%w[abcd], %w[ab\cd]]
}
)
end
it 'handles grouping' do
verify_strings(
/(abc)/ => %w[abc],
/(abc)?/ => [],
/ab(cde)/ => %w[abcde],
/(abc)de/ => %w[abcde],
/ab(cde)fg/ => %w[abcdefg],
/ab(?<name>cd)ef/ => %w[abcdef],
/gh(?>ij)kl/ => %w[ghijkl],
/m(n.*p)q/ => %w[mn pq],
/(?:ab(cd)*){2,3}/ => %w[ab],
/(ab(cd){3})?/ => [],
/(ab(cd)+){2}/ => %w[abcd]
)
end
it 'handles meta characters' do
verify_strings(
/abc\d/ => %w[abc],
/abc\wdef/ => %w[abc def],
/\habc/ => %w[abc]
)
end
it 'handles character properties' do
verify_strings(
/ab\p{Alpha}cd/ => %w[ab cd],
/ab\p{Blank}/ => %w[ab],
/\p{Digit}cd/ => %w[cd]
)
end
it 'handles backreferences' do
verify_strings(
/a(?<group>abc).\k<group>.+/ => %w[aabc]
)
end
it 'handles subexpressions' do
verify_strings(
/\A(?<paren>a\g<paren>*b)+\z/ => %w[a b]
)
end
it 'ignores negative lookaheads' do
verify_strings(
/^(?!.*\bContributing Editor\b).*$/ => %w[],
/abc(?!.*def).*/ => %w[abc],
/(?!.*def)abc/ => %w[abc],
/abc(?!.*def.*).*ghi/ => %w[abc ghi],
/abc(?!.*bcd)def/ => %w[abcdef]
)
end
it 'handles anchors' do
verify_strings(
/^abc/ => %w[abc],
/def$/ => %w[def],
/^abc$/ => %w[abc]
)
end
def verify_strings(hsh)
hsh.each do |regexp, expected|
expect(Capybara::Selector::RegexpDisassembler.new(regexp).substrings).to eq expected
end
verify_alternated_strings(hsh, wrap: true)
end
def verify_alternated_strings(hsh, wrap: false)
hsh.each do |regexp, expected|
expected = [expected] if wrap && (expected != [])
expect(Capybara::Selector::RegexpDisassembler.new(regexp).alternated_substrings).to eq expected
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/css_splitter_spec.rb | spec/css_splitter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Selector::CSS::Splitter do
let :splitter do
described_class.new
end
context 'split not needed' do
it 'normal CSS selector' do
css = 'div[id="abc"]'
expect(splitter.split(css)).to eq [css]
end
it 'comma in strings' do
css = 'div[id="a,bc"]'
expect(splitter.split(css)).to eq [css]
end
it 'comma in pseudo-selector' do
css = 'div.class1:not(.class1, .class2)'
expect(splitter.split(css)).to eq [css]
end
end
context 'split needed' do
it 'root level comma' do
css = 'div.class1, span, p.class2'
expect(splitter.split(css)).to eq ['div.class1', 'span', 'p.class2']
end
it 'root level comma when quotes and pseudo selectors' do
css = 'div.class1[id="abc\\"def,ghi"]:not(.class3, .class4), span[id=\'a"c\\\'de\'], section, #abc\\,def'
expect(splitter.split(css)).to eq ['div.class1[id="abc\\"def,ghi"]:not(.class3, .class4)', 'span[id=\'a"c\\\'de\']', 'section', '#abc\\,def']
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/minitest_spec_spec.rb | spec/minitest_spec_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/minitest'
require 'capybara/minitest/spec'
class MinitestSpecTest < Minitest::Spec
include ::Capybara::DSL
include ::Capybara::Minitest::Assertions
before do
visit('/form')
end
after do
Capybara.reset_sessions!
end
def self.test_order
:sorted
end
it 'supports text expectations' do
_(page).must_have_text('Form', minimum: 1)
_(page).wont_have_text('Not a form')
form = find(:css, 'form', text: 'Title')
_(form).must_have_text('Customer Email')
_(form).wont_have_text('Some other email')
end
it 'supports current_path expectations' do
_(page).must_have_current_path('/form')
_(page).wont_have_current_path('/form2')
end
it 'supports title expectations' do
visit('/with_title')
_(page).must_have_title('Test Title')
_(page).wont_have_title('Not the title')
end
it 'supports xpath expectations' do
_(page).must_have_xpath('.//input[@id="customer_email"]')
_(page).wont_have_xpath('.//select[@id="not_form_title"]')
_(page).wont_have_xpath('.//input[@id="customer_email"]') { |el| el[:id] == 'not_customer_email' }
select = find(:select, 'form_title')
_(select).must_have_xpath('.//option[@class="title"]')
_(select).must_have_xpath('.//option', count: 1) { |option| option[:class] != 'title' && !option.disabled? }
_(select).wont_have_xpath('.//input[@id="customer_email"]')
end
it 'support css expectations' do
_(page).must_have_css('input#customer_email')
_(page).wont_have_css('select#not_form_title')
el = find(:select, 'form_title')
_(el).must_have_css('option.title')
_(el).wont_have_css('input#customer_email')
end
it 'supports link expectations' do
visit('/with_html')
_(page).must_have_link('A link')
_(page).wont_have_link('Not on page')
end
it 'supports button expectations' do
_(page).must_have_button('fresh_btn')
_(page).wont_have_button('not_btn')
end
it 'supports field expectations' do
_(page).must_have_field('customer_email')
_(page).wont_have_field('not_on_the_form')
end
it 'supports select expectations' do
_(page).must_have_select('form_title')
_(page).wont_have_select('not_form_title')
end
it 'supports checked_field expectations' do
_(page).must_have_checked_field('form_pets_dog')
_(page).wont_have_checked_field('form_pets_cat')
end
it 'supports unchecked_field expectations' do
_(page).must_have_unchecked_field('form_pets_cat')
_(page).wont_have_unchecked_field('form_pets_dog')
end
it 'supports table expectations' do
visit('/tables')
_(page).must_have_table('agent_table')
_(page).wont_have_table('not_on_form')
end
it 'supports all_of_selectors expectations' do
_(page).must_have_all_of_selectors(:css, 'select#form_other_title', 'input#form_last_name')
end
it 'supports none_of_selectors expectations' do
_(page).must_have_none_of_selectors(:css, 'input#not_on_page', 'input#also_not_on_page')
end
it 'supports any_of_selectors expectations' do
_(page).must_have_any_of_selectors(:css, 'select#form_other_title', 'input#not_on_page')
end
it 'supports match_selector expectations' do
_(find(:field, 'customer_email')).must_match_selector(:field, 'customer_email')
_(find(:select, 'form_title')).wont_match_selector(:field, 'customer_email')
end
it 'supports match_css expectations' do
_(find(:select, 'form_title')).must_match_css('select#form_title')
_(find(:select, 'form_title')).wont_match_css('select#form_other_title')
end
it 'supports match_xpath expectations' do
_(find(:select, 'form_title')).must_match_xpath('.//select[@id="form_title"]')
_(find(:select, 'form_title')).wont_match_xpath('.//select[@id="not_on_page"]')
end
it 'handles failures' do
_(page).must_have_select('non_existing_form_title')
end
it 'supports style expectations' do
skip "Rack test doesn't support style" if Capybara.current_driver == :rack_test
visit('/with_html')
_(find(:css, '#second')).must_have_style('display' => 'inline') # deprecated
_(find(:css, '#second')).must_match_style('display' => 'inline')
end
it 'supports ancestor expectations' do
option = find(:option, 'Finnish')
_(option).must_have_ancestor(:css, '#form_locale')
end
it 'supports sibling expectations' do
option = find(:css, '#form_title').find(:option, 'Mrs')
_(option).must_have_sibling(:option, 'Mr')
end
end
RSpec.describe 'capybara/minitest/spec' do
before do
Capybara.current_driver = :rack_test
Capybara.app = TestApp
end
after do
Capybara.use_default_driver
end
it 'should support minitest spec' do
output = StringIO.new
reporter = Minitest::SummaryReporter.new(output)
reporter.start
MinitestSpecTest.run reporter, {}
reporter.report
expect(output.string).to include('22 runs, 44 assertions, 1 failures, 0 errors, 1 skips')
# Make sure error messages are displayed
expect(output.string).to match(/expected to find select box "non_existing_form_title" .*but there were no matches/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_firefox_remote.rb | spec/selenium_spec_firefox_remote.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
def selenium_host
ENV.fetch('SELENIUM_HOST', '0.0.0.0')
end
def selenium_port
ENV.fetch('SELENIUM_PORT', 4445)
end
def ensure_selenium_running!
timer = Capybara::Helpers.timer(expire_in: 20)
begin
TCPSocket.open(selenium_host, selenium_port)
rescue StandardError
if timer.expired?
raise 'Selenium is not running. ' \
"You can run a selenium server easily with: \n. " \
'$ docker-compose up -d selenium_firefox'
else
puts 'Waiting for Selenium docker instance...'
sleep 1
retry
end
end
end
Capybara.register_driver :selenium_firefox_remote do |app|
ensure_selenium_running!
url = "http://#{selenium_host}:#{selenium_port}/wd/hub"
browser_options = Selenium::WebDriver::Firefox::Options.new
Capybara::Selenium::Driver.new app,
browser: :remote,
options: browser_options,
url: url
end
FIREFOX_REMOTE_DRIVER = :selenium_firefox_remote
module TestSessions
RemoteFirefox = Capybara::Session.new(FIREFOX_REMOTE_DRIVER, TestApp)
end
skipped_tests = %i[response_headers status_code trigger download]
Capybara::SpecHelper.run_specs TestSessions::RemoteFirefox, FIREFOX_REMOTE_DRIVER.to_s, capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when 'Capybara::Session selenium_firefox_remote node #click should allow multiple modifiers'
skip "Firefox doesn't generate an event for shift+control+click" if firefox_gte?(62, @session)
when 'Capybara::Session selenium_firefox_remote #accept_prompt should accept the prompt with a blank response when there is a default'
pending "Geckodriver doesn't set a blank response in FF < 63 - https://bugzilla.mozilla.org/show_bug.cgi?id=1486485" if firefox_lt?(63, @session)
when 'Capybara::Session selenium_firefox_remote #attach_file with multipart form should fire change once when uploading multiple files from empty'
pending "FF < 62 doesn't support setting all files at once" if firefox_lt?(62, @session)
when 'Capybara::Session selenium_firefox_remote #reset_session! removes ALL cookies'
pending "Geckodriver doesn't provide a way to remove cookies outside the current domain"
when /#accept_confirm should work with nested modals$/
# skip because this is timing based and hence flaky when set to pending
skip 'Broken in FF 63 - https://bugzilla.mozilla.org/show_bug.cgi?id=1487358' if firefox_gte?(63, @session)
when 'Capybara::Session selenium_firefox_remote #fill_in should handle carriage returns with line feeds in a textarea correctly'
pending 'Not sure what firefox is doing here'
when 'Capybara::Session selenium_firefox_remote node #shadow_root should find elements inside the shadow dom using CSS',
'Capybara::Session selenium_firefox_remote node #shadow_root should find nested shadow roots',
'Capybara::Session selenium_firefox_remote node #shadow_root should click on elements',
'Capybara::Session selenium_firefox_remote node #shadow_root should use convenience methods once moved to a descendant of the shadow root',
'Capybara::Session selenium_firefox_remote node #shadow_root should produce error messages when failing',
'Capybara::Session with remote firefox with selenium driver #evaluate_script returns a shadow root'
pending "Firefox doesn't yet have full W3C shadow root support"
when /Capybara::Session selenium_firefox_remote node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
when /Capybara::Session selenium_firefox_remote node #shadow_root/
skip 'Not supported with this geckodriver version' if geckodriver_lt?('0.31.0', @session)
when /Capybara::Session selenium node #set should submit single text input forms if ended with \\n/
pending 'Firefox/geckodriver doesn\'t submit with values ending in \n'
when /Capybara::Session selenium_firefox_remote #click_button should work with popovers/
skip "Firefox doesn't currently support popover functionality"
when /popover/
pending "Firefox doesn't currently support popover functionality"
end
end
RSpec.describe 'Capybara::Session with remote firefox' do
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::RemoteFirefox, FIREFOX_REMOTE_DRIVER
end
it 'is considered to be firefox' do
expect(session.driver.browser.browser).to eq :firefox
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/counter_spec.rb | spec/counter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Server::Middleware::Counter do
let(:counter) { described_class.new }
let(:uri) { '/example' }
describe '#increment' do
it 'successfully' do
counter.increment(uri)
expect(counter).to be_positive
end
end
describe '#decrement' do
before do
counter.increment(uri)
end
context 'successfully' do
it 'with same uri' do
expect(counter).to be_positive
counter.decrement(uri)
expect(counter).not_to be_positive
end
it 'with changed uri' do
expect(counter).to be_positive
counter.decrement('/')
expect(counter).not_to be_positive
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_firefox.rb | spec/selenium_spec_firefox.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
Selenium::WebDriver.logger.ignore(:selenium_manager)
browser_options = Selenium::WebDriver::Firefox::Options.new
browser_options.add_argument '-headless' if ENV['HEADLESS']
# browser_options.add_option("log", {"level": "trace"})
browser_options.profile = Selenium::WebDriver::Firefox::Profile.new.tap do |profile|
profile['browser.download.dir'] = Capybara.save_path
profile['browser.download.folderList'] = 2
profile['browser.helperApps.neverAsk.saveToDisk'] = 'text/csv'
profile['browser.startup.homepage'] = 'about:blank' # workaround bug in Selenium 4 alpha4-7
profile['accessibility.tabfocus'] = 7 # make tab move over links too
end
Capybara.register_driver :selenium_firefox do |app|
# ::Selenium::WebDriver.logger.level = "debug"
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
driver_options = { browser: :firefox, timeout: 31 }.tap do |opts|
opts[options_key] = browser_options
# Get a trace level log from geckodriver
# :driver_opts => { args: ['-vv'] }
end
Capybara::Selenium::Driver.new(app, **driver_options)
end
Capybara.register_driver :selenium_firefox_not_clear_storage do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
driver_options = { browser: :firefox, clear_local_storage: false, clear_session_storage: false }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **driver_options)
end
module TestSessions
SeleniumFirefox = Capybara::Session.new(:selenium_firefox, TestApp)
end
skipped_tests = %i[response_headers status_code trigger]
Capybara::SpecHelper.log_selenium_driver_version(Selenium::WebDriver::Firefox) if ENV['CI']
Capybara::SpecHelper.run_specs TestSessions::SeleniumFirefox, 'selenium', capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when 'Capybara::Session selenium node #click should allow multiple modifiers'
pending "Firefox on OSX doesn't generate an event for shift+control+click" if firefox_gte?(62, @session) && Selenium::WebDriver::Platform.mac?
when /^Capybara::Session selenium node #double_click/
pending "selenium-webdriver/geckodriver doesn't generate double click event" if firefox_lt?(59, @session)
when 'Capybara::Session selenium #accept_prompt should accept the prompt with a blank response when there is a default'
pending "Geckodriver doesn't set a blank response in FF < 63 - https://bugzilla.mozilla.org/show_bug.cgi?id=1486485" if firefox_lt?(63, @session)
when 'Capybara::Session selenium #attach_file with multipart form should fire change once when uploading multiple files from empty'
pending "FF < 62 doesn't support setting all files at once" if firefox_lt?(62, @session)
when 'Capybara::Session selenium #accept_confirm should work with nested modals'
skip 'Broken in 63 <= FF < 69 - https://bugzilla.mozilla.org/show_bug.cgi?id=1487358' if firefox_gte?(63, @session) && firefox_lt?(69, @session)
skip 'Hangs in 69 <= FF < 71 - Dont know what issue for this - previous issue was closed as fixed but it is not' if firefox_gte?(69, @session) && firefox_lt?(71, @session)
skip 'Broken again intermittently in FF 71 - jus skip it' if firefox_lt?(109, @session) # don't really know when it was fixed
when 'Capybara::Session selenium #click_link can download a file'
skip 'Need to figure out testing of file downloading on windows platform' if Gem.win_platform?
when 'Capybara::Session selenium #reset_session! removes ALL cookies'
pending "Geckodriver doesn't provide a way to remove cookies outside the current domain"
when /drag_to.*HTML5/
pending "Firefox < 62 doesn't support a DataTransfer constructor" if firefox_lt?(62.0, @session)
when 'Capybara::Session selenium #accept_alert should handle the alert if the page changes',
'Capybara::Session selenium #accept_alert with an asynchronous alert should accept the alert'
skip 'No clue what Firefox is doing here - works fine on MacOS locally' if firefox_lt?(109, @session) # don't really know when it was fixed
when 'Capybara::Session selenium node #shadow_root should find elements inside the shadow dom using CSS',
'Capybara::Session selenium node #shadow_root should find nested shadow roots',
'Capybara::Session selenium node #shadow_root should click on elements',
'Capybara::Session selenium node #shadow_root should use convenience methods once moved to a descendant of the shadow root',
'Capybara::Session selenium node #shadow_root should produce error messages when failing',
'Capybara::Session with firefox with selenium driver #evaluate_script returns a shadow root'
pending "Firefox doesn't yet have full W3C shadow root support" if firefox_lt?(113, @session)
when 'Capybara::Session selenium #fill_in should handle carriage returns with line feeds in a textarea correctly'
pending 'Not sure what firefox is doing here'
when /Capybara::Session selenium node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
when /Capybara::Session selenium node #shadow_root/
skip 'Not supported with this geckodriver version' if geckodriver_lt?('0.31.0', @session)
when /Capybara::Session selenium node #set should submit single text input forms if ended with \\n/
pending 'Firefox/geckodriver doesn\'t submit with values ending in \n'
when /Capybara::Session selenium #click_button should work with popovers/
skip "Firefox doesn't currently support popover functionality" if firefox_lt?(125, @session)
when /popover/
pending "Firefox doesn't currently support popover functionality" if firefox_lt?(125, @session)
end
end
RSpec.describe 'Capybara::Session with firefox' do # rubocop:disable RSpec/MultipleDescribes
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::SeleniumFirefox, :selenium_firefox
end
describe 'filling in Firefox-specific date and time fields with keystrokes' do
let(:datetime) { Time.new(1983, 6, 19, 6, 30) }
let(:session) { TestSessions::SeleniumFirefox }
before do
session.visit('/form')
end
it 'should fill in a date input with a String' do
session.fill_in('form_date', with: datetime.to_date.iso8601)
session.click_button('awesome')
expect(Date.parse(extract_results(session)['date'])).to eq datetime.to_date
end
it 'should fill in a time input with a String' do
session.fill_in('form_time', with: datetime.to_time.strftime('%T'))
session.click_button('awesome')
results = extract_results(session)['time']
expect(Time.parse(results).strftime('%r')).to eq datetime.strftime('%r')
end
it 'should fill in a datetime input with a String' do
pending 'Need to figure out what string format this will actually accept'
session.fill_in('form_datetime', with: datetime.iso8601)
session.click_button('awesome')
expect(Time.parse(extract_results(session)['datetime'])).to eq datetime
end
end
end
RSpec.describe Capybara::Selenium::Driver do
let(:driver) { described_class.new(TestApp, browser: :firefox, options: browser_options) }
describe '#quit' do
it 'should reset browser when quit' do
expect(driver.browser).to be_truthy
driver.quit
# access instance variable directly so we don't create a new browser instance
expect(driver.instance_variable_get(:@browser)).to be_nil
end
context 'with errors' do
let!(:original_browser) { driver.browser }
after do
# Ensure browser is actually quit so we don't leave hanging processe
RSpec::Mocks.space.proxy_for(original_browser).reset
original_browser.quit
end
it 'warns UnknownError returned during quit because the browser is probably already gone' do
allow(driver).to receive(:warn)
allow(driver.browser).to(
receive(:quit)
.and_raise(Selenium::WebDriver::Error::UnknownError, 'random message')
)
expect { driver.quit }.not_to raise_error
expect(driver.instance_variable_get(:@browser)).to be_nil
expect(driver).to have_received(:warn).with(/random message/)
end
it 'ignores silenced UnknownError returned during quit because the browser is almost definitely already gone' do
allow(driver).to receive(:warn)
allow(driver.browser).to(
receive(:quit)
.and_raise(Selenium::WebDriver::Error::UnknownError, 'Error communicating with the remote browser')
)
expect { driver.quit }.not_to raise_error
expect(driver.instance_variable_get(:@browser)).to be_nil
expect(driver).not_to have_received(:warn)
end
end
end
context 'storage' do
describe '#reset!' do
it 'clears storage by default' do
session = TestSessions::SeleniumFirefox
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.driver.browser.execute_script('return localStorage.length')).to eq(0)
expect(session.driver.browser.execute_script('return sessionStorage.length')).to eq(0)
end
it 'does not clear storage when false' do
session = Capybara::Session.new(:selenium_firefox_not_clear_storage, TestApp)
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.driver.browser.execute_script('return localStorage.length')).to eq(1)
expect(session.driver.browser.execute_script('return sessionStorage.length')).to eq(1)
end
end
end
context 'timeout' do
it 'sets the http client read timeout' do
expect(TestSessions::SeleniumFirefox.driver.browser.send(:bridge).http.read_timeout).to eq 31
end
end
end
RSpec.describe Capybara::Selenium::Node do
describe '#click' do
it 'warns when attempting on a table row' do
session = TestSessions::SeleniumFirefox
session.visit('/tables')
tr = session.find(:css, '#agent_table tr:first-child')
allow(tr.base).to receive(:warn)
tr.click
expect(tr.base).to have_received(:warn).with(/Clicking the first cell in the row instead/)
end
it 'should allow multiple modifiers', requires: [:js] do
session = TestSessions::SeleniumFirefox
session.visit('with_js')
# Firefox v62+ doesn't generate an event for control+shift+click
session.find(:css, '#click-test').click(:alt, :ctrl, :meta)
# it also triggers a contextmenu event when control is held so don't check click type
expect(session).to have_link('Has been alt control meta')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/server_spec.rb | spec/server_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Server do
it 'should spool up a rack server' do
app = proc { |_env| [200, {}, ['Hello Server!']] }
server = described_class.new(app).boot
res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
end
it 'should do nothing when no server given' do
expect do
described_class.new(nil).boot
end.not_to raise_error
end
it 'should bind to the specified host' do
# TODO: travis with jruby in container mode has an issue with this test
skip 'This platform has an issue with this test' if (ENV.fetch('TRAVIS', nil) && (RUBY_ENGINE == 'jruby')) || Gem.win_platform?
begin
app = proc { |_env| [200, {}, ['Hello Server!']] }
Capybara.server_host = '127.0.0.1'
server = described_class.new(app).boot
res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
expect(res).to eq('Hello Server!')
Capybara.server_host = '0.0.0.0'
server = described_class.new(app).boot
res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
expect(res).to eq('Hello Server!')
ensure
Capybara.server_host = nil
end
end
it 'should use specified port' do
Capybara.server_port = 22789
app = proc { |_env| [200, {}, ['Hello Server!']] }
server = described_class.new(app).boot
res = Net::HTTP.start(server.host, 22789) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
Capybara.server_port = nil
end
it 'should use given port' do
app = proc { |_env| [200, {}, ['Hello Server!']] }
server = described_class.new(app, port: 22790).boot
res = Net::HTTP.start(server.host, 22790) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
Capybara.server_port = nil
end
it 'should find an available port' do
responses = ['Hello Server!', 'Hello Second Server!']
apps = responses.map do |response|
proc { |_env| [200, {}, [response]] }
end
servers = apps.map { |app| described_class.new(app).boot }
servers.each_with_index do |server, idx|
result = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
expect(result.body).to include(responses[idx])
end
end
it 'should handle that getting available ports fails randomly' do
# Use a port to force a EADDRINUSE error to be generated
server = TCPServer.new('0.0.0.0', 0)
server_port = server.addr[1]
d_server = instance_double(TCPServer, addr: [nil, server_port, nil, nil], close: nil)
call_count = 0
allow(TCPServer).to receive(:new).and_wrap_original do |m, *args|
call_count.zero? ? d_server : m.call(*args)
ensure
call_count += 1
end
port = described_class.new(Object.new, host: '0.0.0.0').port
expect(port).not_to eq(server_port)
ensure
server&.close
end
it 'should return its #base_url' do
app = proc { |_env| [200, {}, ['Hello Server!']] }
server = described_class.new(app).boot
uri = Addressable::URI.parse(server.base_url)
expect(uri.to_hash).to include(scheme: 'http', host: server.host, port: server.port)
end
it 'should call #clamp on the puma configuration to ensure that environment is a string' do
Capybara.server = :puma
app_proc = proc { |_env| [200, {}, ['Hello Puma!']] }
require 'puma'
allow(Puma::Server).to receive(:new).and_wrap_original do |method, app, events, options|
# If #clamp is not called on the puma config then this will be a Proc
expect(options.fetch(:environment)).to be_a(String)
method.call(app, events, options)
end
server = described_class.new(app_proc).boot
expect(Puma::Server).to have_received(:new).with(
anything,
anything,
satisfy { |opts| opts.final_options[:Port] == server.port }
)
ensure
Capybara.server = :default
end
it 'should not emit any warnings when booting puma' do
Capybara.server = :puma
app_proc = proc { |_env| [200, {}, ['Hello Puma!']] }
require 'puma'
expect do
described_class.new(app_proc).boot
end.not_to output.to_stderr
ensure
Capybara.server = :default
end
it 'should support SSL' do
key = File.join(Dir.pwd, 'spec', 'fixtures', 'key.pem')
cert = File.join(Dir.pwd, 'spec', 'fixtures', 'certificate.pem')
Capybara.server = :puma, { Host: "ssl://#{Capybara.server_host}?key=#{key}&cert=#{cert}" }
app = proc { |_env| [200, {}, ['Hello SSL Server!']] }
server = described_class.new(app).boot
expect do
Net::HTTP.start(server.host, server.port, max_retries: 0) { |http| http.get('/__identify__') }
end.to(raise_error do |e|
expect(e.is_a?(EOFError) || e.is_a?(Net::ReadTimeout)).to be true
end)
res = Net::HTTP.start(server.host, server.port, use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_NONE) do |https|
https.get('/')
end
expect(res.body).to include('Hello SSL Server!')
uri = Addressable::URI.parse(server.base_url)
expect(uri.to_hash).to include(scheme: 'https', host: server.host, port: server.port)
ensure
Capybara.server = :default
end
context 'When Capybara.reuse_server is true' do
let!(:old_reuse_server) { Capybara.reuse_server }
before do
Capybara.reuse_server = true
end
after do
Capybara.reuse_server = old_reuse_server
end
it 'should use the existing server if it already running' do
app = proc { |_env| [200, {}, ['Hello Server!']] }
servers = Array.new(2) { described_class.new(app).boot }
servers.each do |server|
res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
end
expect(servers[0].port).to eq(servers[1].port)
end
it 'detects and waits for all reused server sessions pending requests' do
done = 0
app = proc do |env|
request = Rack::Request.new(env)
sleep request.params['wait_time'].to_f
done += 1
[200, {}, ['Hello Server!']]
end
server1 = described_class.new(app).boot
server2 = described_class.new(app).boot
expect do
start_request(server1, 1.0)
start_request(server2, 3.0)
server1.wait_for_pending_requests
end.to change { done }.from(0).to(2)
expect(server2.send(:pending_requests?)).to be(false)
end
end
context 'When Capybara.reuse_server is false' do
before do
@old_reuse_server = Capybara.reuse_server
Capybara.reuse_server = false
end
after do
Capybara.reuse_server = @old_reuse_server # rubocop:disable RSpec/InstanceVariable
end
it 'should not reuse an already running server' do
app = proc { |_env| [200, {}, ['Hello Server!']] }
servers = Array.new(2) { described_class.new(app).boot }
servers.each do |server|
res = Net::HTTP.start(server.host, server.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
end
expect(servers[0].port).not_to eq(servers[1].port)
end
it 'detects and waits for only one sessions pending requests' do
done = 0
app = proc do |env|
request = Rack::Request.new(env)
sleep request.params['wait_time'].to_f
done += 1
[200, {}, ['Hello Server!']]
end
server1 = described_class.new(app).boot
server2 = described_class.new(app).boot
expect do
start_request(server1, 1.0)
start_request(server2, 3.0)
server1.wait_for_pending_requests
end.to change { done }.from(0).to(1)
expect(server2.send(:pending_requests?)).to be(true)
expect do
server2.wait_for_pending_requests
end.to change { done }.from(1).to(2)
end
end
it 'should raise server errors when the server errors before the timeout' do
Capybara.register_server :kaboom do
sleep 0.1
raise 'kaboom'
end
Capybara.server = :kaboom
expect do
described_class.new(proc { |e| }).boot
end.to raise_error(RuntimeError, 'kaboom')
ensure
Capybara.server = :default
end
it 'should raise an error when there are pending requests' do
app = proc do |env|
request = Rack::Request.new(env)
sleep request.params['wait_time'].to_f
[200, {}, ['Hello Server!']]
end
server = described_class.new(app).boot
expect do
start_request(server, 59.0)
server.wait_for_pending_requests
end.not_to raise_error
expect do
start_request(server, 61.0)
server.wait_for_pending_requests
end.to raise_error('Requests did not finish in 60 seconds: ["/?wait_time=61.0"]')
end
it 'is not #responsive? when Net::HTTP raises a SystemCallError' do
app = -> { [200, {}, ['Hello, world']] }
server = described_class.new(app)
allow(Net::HTTP).to receive(:start).and_raise(SystemCallError.allocate)
expect(server.responsive?).to be false
end
[EOFError, Net::ReadTimeout].each do |err|
it "should attempt an HTTPS connection if HTTP connection returns #{err}" do
app = -> { [200, {}, ['Hello, world']] }
ordered_errors = [Errno::ECONNREFUSED, err]
allow(Net::HTTP).to receive(:start).with(anything, anything, hash_excluding(:use_ssl)) do
raise ordered_errors.shift
end
response = Net::HTTPSuccess.allocate
allow(response).to receive(:body).and_return app.object_id.to_s
allow(Net::HTTP).to receive(:start).with(anything, anything, hash_including(use_ssl: true)).and_return(response).once
described_class.new(app).boot
expect(Net::HTTP).to have_received(:start).exactly(3).times
end
end
def start_request(server, wait_time)
# Start request, but don't wait for it to finish
socket = TCPSocket.new(server.host, server.port)
socket.write "GET /?wait_time=#{wait_time} HTTP/1.0\r\n\r\n"
sleep 0.1
socket.close
sleep 0.1
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_ie.rb | spec/selenium_spec_ie.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
# if ENV['CI']
# if ::Selenium::WebDriver::Service.respond_to? :driver_path=
# ::Selenium::WebDriver::IE::Service
# else
# ::Selenium::WebDriver::IE
# end.driver_path = 'C:\Tools\WebDriver\IEDriverServer.exe'
# end
def selenium_host
ENV.fetch('SELENIUM_HOST', '192.168.56.102')
end
def selenium_port
ENV.fetch('SELENIUM_PORT', 4444)
end
def server_host
ENV.fetch('SERVER_HOST', '10.24.4.135')
end
Capybara.register_driver :selenium_ie do |app|
# ::Selenium::WebDriver.logger.level = "debug"
options = Selenium::WebDriver::IE::Options.new
# options.require_window_focus = true
# options.add_option("log", {"level": "trace"})
if ENV['REMOTE']
Capybara.server_host = server_host
url = "http://#{selenium_host}:#{selenium_port}/wd/hub"
Capybara::Selenium::Driver.new(app,
browser: :remote,
options: options,
url: url)
else
Capybara::Selenium::Driver.new(
app,
browser: :ie,
options: options
)
end
end
module TestSessions
SeleniumIE = Capybara::Session.new(:selenium_ie, TestApp)
end
TestSessions::SeleniumIE.current_window.resize_to(800, 500)
skipped_tests = %i[response_headers status_code trigger modals hover form_attribute windows]
Capybara::SpecHelper.log_selenium_driver_version(Selenium::WebDriver::IE) if ENV['CI']
TestSessions::SeleniumIE.current_window.resize_to(1600, 1200)
Capybara::SpecHelper.run_specs TestSessions::SeleniumIE, 'selenium', capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when /#refresh it reposts$/
skip 'IE insists on prompting without providing a way to suppress'
when /#click_link can download a file$/
skip 'Not sure how to configure IE for automatic downloading'
when /#fill_in with Date /
pending "IE 11 doesn't support date input types"
when /#click_link_or_button with :disabled option happily clicks on links which incorrectly have the disabled attribute$/
skip 'IE 11 obeys non-standard disabled attribute on anchor tag'
when /#click should allow modifiers$/, /#double_click should allow modifiers$/
pending "Doesn't work with IE for some unknown reason$"
pending "Doesn't work with IE for some unknown reason$"
when /#click should allow multiple modifiers$/, /#right_click should allow modifiers$/
skip "Windows can't :meta click because :meta triggers start menu"
when /#double_click should allow multiple modifiers$/
skip "Windows can't :alt double click due to being properties shortcut"
when /#has_css\? should support case insensitive :class and :id options$/
pending "IE doesn't support case insensitive CSS selectors"
when /#reset_session! removes ALL cookies$/
pending "IE driver doesn't provide a way to remove ALL cookies"
when /#click_button should send button in document order$/
pending "IE 11 doesn't support the 'form' attribute"
when /#click_button should follow permanent redirects that maintain method$/
pending "Window 7 and 8.1 don't support 308 http status code"
when /#scroll_to can scroll an element to the center of the viewport$/,
/#scroll_to can scroll an element to the center of the scrolling element$/
pending "IE doesn't support ScrollToOptions"
when /#attach_file with multipart form should fire change once for each set of files uploaded$/,
/#attach_file with multipart form should fire change once when uploading multiple files from empty$/,
/#attach_file with multipart form should not break when using HTML5 multiple file input uploading multiple files$/
pending "IE requires all files be uploaded from same directory. Selenium doesn't provide that." if ENV['REMOTE']
when %r{#attach_file with multipart form should send content type image/jpeg when uploading an image$}
pending 'IE gets text/plain type for some reason'
# when /#click should not retry clicking when wait is disabled$/
# Fixed in IEDriverServer 3.141.0.5
# pending "IE driver doesn't error when clicking on covered elements, it just clicks the wrong element"
when /#click should go to the same page if href is blank$/
pending 'IE treats blank href as a parent request (against HTML spec)'
when /#attach_file with a block/
skip 'Hangs IE testing for unknown reason'
when /drag_to.*HTML5/
pending "IE doesn't support a DataTransfer constructor"
when /template elements should not be visible/
skip "IE doesn't support template elements"
when /Element#drop/
pending "IE doesn't support DataTransfer constructor"
when /Capybara::Session selenium_chrome node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
end
end
RSpec.describe 'Capybara::Session with Internet Explorer', capybara_skip: skipped_tests do # rubocop:disable RSpec/MultipleDescribes
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::SeleniumIE, :selenium_ie
end
end
RSpec.describe Capybara::Selenium::Node do
it '#right_click should allow modifiers' do
# pending "Actions API doesn't appear to work for this"
session = TestSessions::SeleniumIE
session.visit('/with_js')
el = session.find(:css, '#click-test')
el.right_click(:control)
expect(session).to have_link('Has been control right clicked')
end
it '#click should allow multiple modifiers' do
# pending "Actions API doesn't appear to work for this"
session = TestSessions::SeleniumIE
session.visit('with_js')
# IE triggers system behavior with :meta so can't use those here
session.find(:css, '#click-test').click(:ctrl, :shift, :alt)
expect(session).to have_link('Has been alt control shift clicked')
end
it '#double_click should allow modifiers' do
# pending "Actions API doesn't appear to work for this"
session = TestSessions::SeleniumIE
session.visit('/with_js')
session.find(:css, '#click-test').double_click(:shift)
expect(session).to have_link('Has been shift double clicked')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/shared_selenium_node.rb | spec/shared_selenium_node.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
RSpec.shared_examples 'Capybara::Node' do |session, _mode|
let(:session) { session }
describe '#content_editable?' do
it 'returns true when the element is content editable' do
session.visit('/with_js')
expect(session.find(:css, '#existing_content_editable').base.content_editable?).to be true
expect(session.find(:css, '#existing_content_editable_child').base.content_editable?).to be true
end
it 'returns false when the element is not content editable' do
session.visit('/with_js')
expect(session.find(:css, '#drag').base.content_editable?).to be false
end
end
describe '#send_keys' do
it 'should process space' do
session.visit('/form')
session.find(:css, '#address1_city').send_keys('ocean', [:shift, :space, 'side'])
expect(session.find(:css, '#address1_city').value).to eq 'ocean SIDE'
end
end
describe '#[]' do
it 'should work for spellcheck' do
session.visit('/with_html')
expect(session.find('//input[@spellcheck="TRUE"]')[:spellcheck]).to eq('true')
expect(session.find('//input[@spellcheck="FALSE"]')[:spellcheck]).to eq('false')
end
end
describe '#set' do
it 'respects maxlength when using rapid set' do
session.visit('/form')
inp = session.find(:css, '#long_length')
value = (0...50).map { |i| ((i % 26) + 65).chr }.join
inp.set(value, rapid: true)
expect(inp.value).to eq value[0...35]
end
end
describe '#visible?' do
let(:bridge) do
session.driver.browser.send(:bridge)
end
around do |example|
native_displayed = session.driver.options[:native_displayed]
example.run
session.driver.options[:native_displayed] = native_displayed
end
before do
allow(bridge).to receive(:execute_atom).and_call_original
end
it 'will use native displayed if told to' do
session.driver.options[:native_displayed] = true
session.visit('/form')
session.find(:css, '#address1_city', visible: true)
expect(bridge).not_to have_received(:execute_atom)
end
it "won't use native displayed if told not to" do
session.driver.options[:native_displayed] = false
session.visit('/form')
session.find(:css, '#address1_city', visible: true)
expect(bridge).to have_received(:execute_atom).with(:isDisplayed, any_args)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/whitespace_normalizer_spec.rb | spec/whitespace_normalizer_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/node/whitespace_normalizer'
RSpec.describe Capybara::Node::WhitespaceNormalizer do
subject(:normalizer) do
klass = Class.new do
include Capybara::Node::WhitespaceNormalizer
end
klass.new
end
let(:text_needing_correction) do
<<~TEXT
Some #{described_class::NON_BREAKING_SPACE}text
#{described_class::RIGHT_TO_LEFT_MARK}
#{described_class::ZERO_WIDTH_SPACE * 30}
#{described_class::LEFT_TO_RIGHT_MARK}
Here
TEXT
end
describe '#normalize_spacing' do
it 'does nothing to text not containing special characters' do
expect(normalizer.normalize_spacing('text')).to eq('text')
end
it 'compresses excess breaking spacing' do
expect(
normalizer.normalize_spacing(text_needing_correction)
).to eq('Some text Here')
end
end
describe '#normalize_visible_spacing' do
it 'does nothing to text not containing special characters' do
expect(normalizer.normalize_visible_spacing('text')).to eq('text')
end
it 'compresses excess breaking visible spacing' do
expect(
normalizer.normalize_visible_spacing(text_needing_correction)
).to eq <<~TEXT.chomp
Some text
#{described_class::RIGHT_TO_LEFT_MARK}
#{described_class::ZERO_WIDTH_SPACE * 30}
#{described_class::LEFT_TO_RIGHT_MARK}
Here
TEXT
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_safari.rb | spec/selenium_spec_safari.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
SAFARI_DRIVER = :selenium_safari
# if ::Selenium::WebDriver::Service.respond_to? :driver_path=
# ::Selenium::WebDriver::Safari::Service
# else
# ::Selenium::WebDriver::Safari
# end.driver_path = '/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver'
browser_options = Selenium::WebDriver::Safari::Options.new
# browser_options.headless! if ENV['HEADLESS']
Capybara.register_driver :selenium_safari do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
driver_options = { browser: :safari, timeout: 30 }.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **driver_options).tap do |driver|
# driver.browser.download_path = Capybara.save_path
end
end
Capybara.register_driver :selenium_safari_not_clear_storage do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
driver_options = {
browser: :safari,
clear_local_storage: false,
clear_session_storage: false,
timeout: 30
}.tap do |opts|
opts[options_key] = browser_options
end
Capybara::Selenium::Driver.new(app, **driver_options)
end
module TestSessions
Safari = Capybara::Session.new(SAFARI_DRIVER, TestApp)
end
skipped_tests = %i[response_headers status_code trigger windows drag]
Capybara::SpecHelper.log_selenium_driver_version(Selenium::WebDriver::Safari) if ENV['CI']
Capybara::SpecHelper.run_specs TestSessions::Safari, SAFARI_DRIVER.to_s, capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when /click_link can download a file/
skip "safaridriver doesn't provide a way to set the download directory"
when /Capybara::Session selenium_safari Capybara::Window#maximize/
pending "Safari headless doesn't support maximize" if ENV['HEADLESS']
when /Capybara::Session selenium_safari #visit without a server/,
/Capybara::Session selenium_safari #visit with Capybara.app_host set should override server/,
/Capybara::Session selenium_safari #reset_session! When reuse_server == false raises any standard errors caught inside the server during a second session/
skip "Safari webdriver doesn't support multiple sessions"
when /Capybara::Session selenium_safari #click_link with alternative text given to a contained image/,
'Capybara::Session selenium_safari #click_link_or_button with enable_aria_label should click on link'
pending 'safaridriver thinks these links are non-interactable for some unknown reason'
when /Capybara::Session selenium_safari #attach_file with a block can upload by clicking the file input/
skip "safaridriver doesn't allow clicking on file inputs"
when /Capybara::Session selenium_safari #within_frame works if the frame is closed/,
/Capybara::Session selenium_safari #switch_to_frame works if the frame is closed/
skip 'Safari has a race condition when clicking an element that causes the frame to close. It will sometimes raise a NoSuchFrameError'
when /Capybara::Session selenium_safari #reset_session! removes ALL cookies/
skip 'Safari webdriver can only remove cookies for the current domain'
when /Capybara::Session selenium_safari #refresh it reposts/
skip "Safari opens an alert that can't be closed"
when 'Capybara::Session selenium_safari node #double_click should allow to adjust the offset',
'Capybara::Session selenium_safari node #double_click should double click an element'
pending "safardriver doesn't generate a double click event"
when 'Capybara::Session selenium_safari node #double_click should allow modifiers'
pending "safaridriver doesn't generate double click with key modifiers"
when /when w3c_click_offset is true should offset/
pending 'w3c_click_offset is not currently supported with safaridriver'
when 'Capybara::Session selenium_safari #go_back should fetch a response from the driver from the previous page',
'Capybara::Session selenium_safari #go_forward should fetch a response from the driver from the previous page'
skip 'safaridriver loses the ability to find elements in the document after `go_back`'
when 'Capybara::Session selenium node #shadow_root should get the shadow root',
'Capybara::Session selenium node #shadow_root should find elements inside the shadow dom using CSS',
'Capybara::Session selenium node #shadow_root should find nested shadow roots'
pending "Safari doesn't yet have W3C shadow root support"
when /Capybara::Session selenium_chrome node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
end
end
RSpec.describe 'Capybara::Session with safari' do
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::Safari, SAFARI_DRIVER
end
context 'storage' do
describe '#reset!' do
it 'clears storage by default' do
session = TestSessions::Safari
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).to be_empty
end
it 'does not clear storage when false' do
skip "Safari webdriver doesn't support multiple sessions"
session = Capybara::Session.new(:selenium_safari_not_clear_storage, TestApp)
session.visit('/with_js')
session.find(:css, '#set-storage').click
session.reset!
session.visit('/with_js')
expect(session.evaluate_script('Object.keys(localStorage)')).not_to be_empty
expect(session.evaluate_script('Object.keys(sessionStorage)')).not_to be_empty
end
end
end
context 'timeout' do
it 'sets the http client read timeout' do
expect(TestSessions::Safari.driver.browser.send(:bridge).http.read_timeout).to eq 30
end
end
describe 'filling in Safari-specific date and time fields with keystrokes' do
let(:datetime) { Time.new(1983, 6, 19, 6, 30) }
let(:session) { TestSessions::Safari }
before do
session.visit('/form')
end
it 'should fill in a date input with a String' do
session.fill_in('form_date', with: '06/19/1983')
session.click_button('awesome')
expect(Date.parse(extract_results(session)['date'])).to eq datetime.to_date
end
it 'should fill in a time input with a String' do
# Safari doesn't support time inputs - so this is just a text input
session.fill_in('form_time', with: '06:30A')
session.click_button('awesome')
results = extract_results(session)['time']
expect(Time.parse(results).strftime('%r')).to eq datetime.strftime('%r')
end
it 'should fill in a datetime input with a String' do
pending "Safari doesn't support datetime inputs"
session.fill_in('form_datetime', with: "06/19/1983\t06:30A")
session.click_button('awesome')
expect(Time.parse(extract_results(session)['datetime'])).to eq datetime
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'rspec/expectations'
require 'selenium_statistics'
if ENV['TRAVIS']
require 'coveralls'
Coveralls.wear! do
add_filter '/lib/capybara/driver/'
add_filter '/lib/capybara/registrations/'
end
end
require 'capybara/spec/spec_helper'
module Capybara
module SpecHelper
def firefox?(session)
browser_name(session) == :firefox &&
((defined?(::Selenium::WebDriver::VERSION) && (Gem::Version.new(::Selenium::WebDriver::VERSION) >= Gem::Version.new('4'))) ||
session.driver.browser.capabilities.is_a?(::Selenium::WebDriver::Remote::W3C::Capabilities))
end
def firefox_lt?(version, session)
firefox?(session) && (session.driver.browser.capabilities[:browser_version].to_f < version)
end
def firefox_gte?(version, session)
firefox?(session) && (session.driver.browser.capabilities[:browser_version].to_f >= version)
end
def geckodriver_version(session)
Gem::Version.new(session.driver.browser.capabilities['moz:geckodriverVersion'])
end
def geckodriver_gte?(version, session)
firefox?(session) && geckodriver_version(session) >= Gem::Version.new(version)
end
def geckodriver_lt?(version, session)
firefox?(session) && geckodriver_version(session) < Gem::Version.new(version)
end
def chrome?(session)
browser_name(session) == :chrome
end
def chrome_version(session)
(session.driver.browser.capabilities[:browser_version] ||
session.driver.browser.capabilities[:version]).to_f
end
def chrome_lt?(version, session)
chrome?(session) && (chrome_version(session) < version)
end
def chrome_gte?(version, session)
chrome?(session) && (chrome_version(session) >= version)
end
def chromedriver_version(session)
Gem::Version.new(session.driver.browser.capabilities['chrome']['chromedriverVersion'].split[0])
end
def chromedriver_gte?(version, session)
chrome?(session) && chromedriver_version(session) >= Gem::Version.new(version)
end
def chromedriver_lt?(version, session)
chrome?(session) && chromedriver_version(session) < Gem::Version.new(version)
end
def selenium?(session)
session.driver.is_a? Capybara::Selenium::Driver
end
def selenium_lt?(version, session)
selenium?(session) &&
Gem::Version.new(::Selenium::WebDriver::VERSION) < Gem::Version.new(version)
end
def edge?(session)
browser_name(session).to_s.start_with?('edge')
end
def legacy_edge?(session)
browser_name(session) == :edge
end
def edge_lt?(version, session)
edge?(session) && (chrome_version(session) < version)
end
def edge_gte?(version, session)
edge?(session) && (chrome_version(session) >= version)
end
def ie?(session)
%i[internet_explorer ie].include?(browser_name(session))
end
def safari?(session)
%i[safari Safari Safari_Technology_Preview].include?(browser_name(session))
end
def browser_name(session)
session.driver.browser.browser if session.respond_to?(:driver)
end
def remote?(session)
session.driver.browser.is_a? ::Selenium::WebDriver::Remote::Driver
end
def self.log_selenium_driver_version(mod)
mod = mod::Service if ::Selenium::WebDriver::Service.respond_to? :driver_path
path = mod.driver_path
path = path.call if path.respond_to? :call
$stdout.puts `#{path.gsub(' ', '\ ')} --version` if path
end
end
end
RSpec.configure do |config|
Capybara::SpecHelper.configure(config)
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run_including focus_: true unless ENV['CI']
config.run_all_when_everything_filtered = true
config.after(:suite) { SeleniumStatistics.print_results }
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/filter_set_spec.rb | spec/filter_set_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Selector::FilterSet do
after do
described_class.remove(:test)
end
it 'allows node filters' do
fs = described_class.add(:test) do
node_filter(:node_test, :boolean) { |_node, _value| true }
expression_filter(:expression_test, :boolean) { |_expr, _value| true }
end
expect(fs.node_filters.keys).to include(:node_test)
expect(fs.node_filters.keys).not_to include(:expression_test)
end
it 'allows expression filters' do
fs = described_class.add(:test) do
node_filter(:node_test, :boolean) { |_node, _value| true }
expression_filter(:expression_test, :boolean) { |_expr, _value| true }
end
expect(fs.expression_filters.keys).to include(:expression_test)
expect(fs.expression_filters.keys).not_to include(:node_test)
end
it 'allows node filter and expression filter with the same name' do
fs = described_class.add(:test) do
node_filter(:test, :boolean) { |_node, _value| true }
expression_filter(:test, :boolean) { |_expr, _value| true }
end
expect(fs.expression_filters[:test]).not_to eq fs.node_filters[:test]
end
it 'allows `filter` as an alias of `node_filter`' do
fs = described_class.add(:test) do
filter(:node_test, :boolean) { |_node, _value| true }
end
expect(fs.node_filters.keys).to include(:node_test)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/xpath_builder_spec.rb | spec/xpath_builder_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# rubocop:disable RSpec/InstanceVariable
RSpec.describe Capybara::Selector::XPathBuilder do
let :builder do
described_class.new(@xpath)
end
context 'add_attribute_conditions' do
it 'adds a single string condition to a single selector' do
@xpath = './/div'
selector = builder.add_attribute_conditions(random: 'abc')
expect(selector).to eq %((.//div)[(./@random = 'abc')])
end
it 'adds multiple string conditions to a single selector' do
@xpath = './/div'
selector = builder.add_attribute_conditions(random: 'abc', other: 'def')
expect(selector).to eq %(((.//div)[(./@random = 'abc')])[(./@other = 'def')])
end
it 'adds a single string condition to a multiple selector' do
@xpath = XPath.descendant(:div, :ul)
selector = builder.add_attribute_conditions(random: 'abc')
expect(selector.to_s).to eq @xpath[XPath.attr(:random) == 'abc'].to_s
end
it 'adds multiple string conditions to a multiple selector' do
@xpath = XPath.descendant(:div, :ul)
selector = builder.add_attribute_conditions(random: 'abc', other: 'def')
expect(selector.to_s).to eq %(.//*[self::div | self::ul][(./@random = 'abc')][(./@other = 'def')])
end
it 'adds simple regexp conditions to a single selector' do
@xpath = XPath.descendant(:div)
selector = builder.add_attribute_conditions(random: /abc/, other: /def/)
expect(selector.to_s).to eq %(.//div[./@random[contains(., 'abc')]][./@other[contains(., 'def')]])
end
it 'adds wildcard regexp conditions to a single selector' do
@xpath = './/div'
selector = builder.add_attribute_conditions(random: /abc.*def/, other: /def.*ghi/)
expect(selector).to eq %(((.//div)[./@random[(contains(., 'abc') and contains(., 'def'))]])[./@other[(contains(., 'def') and contains(., 'ghi'))]])
end
it 'adds alternated regexp conditions to a single selector' do
@xpath = XPath.descendant(:div)
selector = builder.add_attribute_conditions(random: /abc|def/, other: /def|ghi/)
expect(selector.to_s).to eq %(.//div[./@random[(contains(., 'abc') or contains(., 'def'))]][./@other[(contains(., 'def') or contains(., 'ghi'))]])
end
it 'adds alternated regexp conditions to a multiple selector' do
@xpath = XPath.descendant(:div, :ul)
selector = builder.add_attribute_conditions(other: /def.*ghi|jkl/)
expect(selector.to_s).to eq %(.//*[self::div | self::ul][./@other[((contains(., 'def') and contains(., 'ghi')) or contains(., 'jkl'))]])
end
it "returns original selector when regexp can't be substringed" do
@xpath = './/div'
selector = builder.add_attribute_conditions(other: /.+/)
expect(selector).to eq '(.//div)[./@other]'
end
context ':class' do
it 'handles string' do
@xpath = './/a'
selector = builder.add_attribute_conditions(class: 'my_class')
expect(selector).to eq %((.//a)[contains(concat(' ', normalize-space(./@class), ' '), ' my_class ')])
end
it 'handles negated strings' do
@xpath = XPath.descendant(:a)
selector = builder.add_attribute_conditions(class: '!my_class')
expect(selector.to_s).to eq @xpath[!XPath.attr(:class).contains_word('my_class')].to_s
end
it 'handles array of strings' do
@xpath = './/a'
selector = builder.add_attribute_conditions(class: %w[my_class my_other_class])
expect(selector).to eq %((.//a)[(contains(concat(' ', normalize-space(./@class), ' '), ' my_class ') and contains(concat(' ', normalize-space(./@class), ' '), ' my_other_class '))])
end
it 'handles array of string when negated included' do
@xpath = XPath.descendant(:a)
selector = builder.add_attribute_conditions(class: %w[my_class !my_other_class])
expect(selector.to_s).to eq @xpath[XPath.attr(:class).contains_word('my_class') & !XPath.attr(:class).contains_word('my_other_class')].to_s
end
end
end
end
# rubocop:enable RSpec/InstanceVariable
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/selenium_spec_chrome_remote.rb | spec/selenium_spec_chrome_remote.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
require 'shared_selenium_session'
require 'shared_selenium_node'
require 'rspec/shared_spec_matchers'
def selenium_host
ENV.fetch('SELENIUM_HOST', '0.0.0.0')
end
def selenium_port
ENV.fetch('SELENIUM_PORT', 4444)
end
def ensure_selenium_running!
timer = Capybara::Helpers.timer(expire_in: 20)
begin
TCPSocket.open(selenium_host, selenium_port)
rescue StandardError
if timer.expired?
raise 'Selenium is not running. ' \
"You can run a selenium server easily with: \n " \
'$ docker-compose up -d selenium_chrome'
else
puts 'Waiting for Selenium docker instance...'
sleep 1
retry
end
end
end
def selenium_gte?(version)
defined?(Selenium::WebDriver::VERSION) && (Gem::Version.new(Selenium::WebDriver::VERSION) >= Gem::Version.new(version))
end
Capybara.register_driver :selenium_chrome_remote do |app|
ensure_selenium_running!
url = "http://#{selenium_host}:#{selenium_port}/wd/hub"
browser_options = Selenium::WebDriver::Chrome::Options.new
Capybara::Selenium::Driver.new app,
browser: :remote,
options: browser_options,
url: url
end
CHROME_REMOTE_DRIVER = :selenium_chrome_remote
module TestSessions
Chrome = Capybara::Session.new(CHROME_REMOTE_DRIVER, TestApp)
end
skipped_tests = %i[response_headers status_code trigger download]
Capybara::SpecHelper.run_specs TestSessions::Chrome, CHROME_REMOTE_DRIVER.to_s, capybara_skip: skipped_tests do |example|
case example.metadata[:full_description]
when /Capybara::Session selenium_chrome_remote node #shadow_root should get visible text/
pending "Selenium doesn't currently support getting visible text for shadow root elements"
when /Capybara::Session selenium_chrome_remote node #shadow_root/
skip 'Not supported with this chromedriver version' if chromedriver_lt?('96.0', @session)
end
end
RSpec.describe 'Capybara::Session with remote Chrome' do
include Capybara::SpecHelper
['Capybara::Session', 'Capybara::Node', Capybara::RSpecMatchers].each do |examples|
include_examples examples, TestSessions::Chrome, CHROME_REMOTE_DRIVER
end
it 'is considered to be chrome' do
expect(session.driver.browser.browser).to eq :chrome
end
describe 'log access' do
let(:logs) do
session.driver.browser.then do |chrome_driver|
chrome_driver.respond_to?(:logs) ? chrome_driver : chrome_driver.manage
end.logs
end
it 'does not error when getting log types' do
expect do
logs.available_types
end.not_to raise_error
end
it 'does not error when getting logs' do
expect do
logs.get(:browser)
end.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/shared_selenium_session.rb | spec/shared_selenium_session.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
RSpec.shared_examples 'Capybara::Session' do |session, mode|
let(:session) { session }
context 'with selenium driver' do
describe '#driver' do
it 'should be a selenium driver' do
expect(session.driver).to be_an_instance_of(Capybara::Selenium::Driver)
end
end
describe '#mode' do
it 'should remember the mode' do
expect(session.mode).to eq(mode)
end
end
describe '#reset!' do
it 'freshly reset session should not be touched' do
session.instance_variable_set(:@touched, true)
session.reset!
expect(session.instance_variable_get(:@touched)).to be false
end
end
describe 'exit codes' do
let(:env) { { 'SELENIUM_BROWSER' => session.driver.options[:browser].to_s } }
let!(:orig_dir) { Dir.getwd }
before do
Dir.chdir(File.join(File.dirname(__FILE__), '..'))
end
after do
Dir.chdir(orig_dir)
end
it 'should have return code 1 when running selenium_driver_rspec_failure.rb' do
skip 'only setup for local non-headless' if headless_or_remote?
skip 'Not setup for edge' if edge?(session)
system(env, 'rspec spec/fixtures/selenium_driver_rspec_failure.rb', out: File::NULL, err: File::NULL)
expect($CHILD_STATUS.exitstatus).to eq(1)
end
it 'should have return code 0 when running selenium_driver_rspec_success.rb' do
skip 'only setup for local non-headless' if headless_or_remote?
skip 'Not setup for edge' if edge?(session)
system(env, 'rspec spec/fixtures/selenium_driver_rspec_success.rb', out: File::NULL, err: File::NULL)
expect($CHILD_STATUS.exitstatus).to eq(0)
end
end
describe '#accept_alert', requires: [:modals] do
it 'supports a blockless mode' do
session.visit('/with_js')
session.click_link('Open alert')
session.accept_alert
expect { session.driver.browser.switch_to.alert }.to raise_error(session.driver.send(:modal_error))
end
it 'can be called before visiting' do
session.accept_alert 'Initial alert' do
session.visit('/initial_alert')
end
expect(session).to have_text('Initial alert page')
end
end
describe '#fill_in_with empty string and no options' do
it 'should trigger change when clearing a field' do
session.visit('/with_js')
session.fill_in('with_change_event', with: '')
# click outside the field to trigger the change event
session.find(:css, 'body').click
expect(session).to have_selector(:css, '.change_event_triggered', match: :one)
end
end
describe '#fill_in with { :clear => :backspace } fill_option', requires: [:js] do
before do
# Firefox has an issue with change events if the main window doesn't think it's focused
session.execute_script('window.focus()')
end
it 'should fill in a field, replacing an existing value' do
session.visit('/form')
session.fill_in('form_first_name',
with: 'Harry',
fill_options: { clear: :backspace })
expect(session.find(:fillable_field, 'form_first_name').value).to eq('Harry')
end
it 'should fill in a field, replacing an existing value, even with caret position' do
session.visit('/form')
session.find(:css, '#form_first_name').execute_script <<-JS
this.focus();
this.setSelectionRange(0, 0);
JS
session.fill_in('form_first_name',
with: 'Harry',
fill_options: { clear: :backspace })
expect(session.find(:fillable_field, 'form_first_name').value).to eq('Harry')
end
it 'should fill in if the option is set via global option' do
Capybara.default_set_options = { clear: :backspace }
session.visit('/form')
session.fill_in('form_first_name', with: 'Thomas')
expect(session.find(:fillable_field, 'form_first_name').value).to eq('Thomas')
end
it 'should only trigger onchange once' do
session.visit('/with_js')
sleep 2 if safari?(session) # Safari needs a delay (to load event handlers maybe ???)
session.fill_in('with_change_event',
with: 'some value',
fill_options: { clear: :backspace })
# click outside the field to trigger the change event
session.find(:css, '#with_focus_event').click
expect(session.find(:css, '.change_event_triggered', match: :one, wait: 5)).to have_text 'some value'
end
it 'should trigger change when clearing field' do
session.visit('/with_js')
session.fill_in('with_change_event',
with: '',
fill_options: { clear: :backspace })
# click outside the field to trigger the change event
session.find(:css, '#with_focus_event').click
expect(session).to have_selector(:css, '.change_event_triggered', match: :one, wait: 5)
end
it 'should trigger input event field_value.length times' do
session.visit('/with_js')
session.fill_in('with_change_event',
with: '',
fill_options: { clear: :backspace })
# click outside the field to trigger the change event
# session.find(:css, 'body').click
session.find(:css, 'h1', text: 'FooBar').click
expect(session).to have_xpath('//p[@class="input_event_triggered"]', count: 13)
end
end
describe '#fill_in with { clear: :none } fill_options' do
it 'should append to content in a field' do
pending 'Safari overwrites by default - need to figure out a workaround' if safari?(session)
session.visit('/form')
session.fill_in('form_first_name',
with: 'Harry',
fill_options: { clear: :none })
expect(session.find(:fillable_field, 'form_first_name').value).to eq('JohnHarry')
end
it 'works with rapid fill' do
pending 'Safari overwrites by default - need to figure out a workaround' if safari?(session)
long_string = (0...60).map { |i| ((i % 26) + 65).chr }.join
session.visit('/form')
session.fill_in('form_first_name', with: long_string, fill_options: { clear: :none })
expect(session.find(:fillable_field, 'form_first_name').value).to eq("John#{long_string}")
end
end
describe '#fill_in with Date' do
before do
session.visit('/form')
session.find(:css, '#form_date').execute_script <<-JS
window.capybara_formDateFiredEvents = [];
var fd = this;
['focus', 'input', 'change'].forEach(function(eventType) {
fd.addEventListener(eventType, function() { window.capybara_formDateFiredEvents.push(eventType); });
});
JS
# work around weird FF issue where it would create an extra focus issue in some cases
session.find(:css, 'h1', text: 'Form').click
# session.find(:css, 'body').click
end
it 'should generate standard events on changing value' do
pending "IE 11 doesn't support date input type" if ie?(session)
session.fill_in('form_date', with: Date.today)
expect(session.evaluate_script('window.capybara_formDateFiredEvents')).to eq %w[focus input change]
end
it 'should not generate input and change events if the value is not changed' do
pending "IE 11 doesn't support date input type" if ie?(session)
session.fill_in('form_date', with: Date.today)
session.fill_in('form_date', with: Date.today)
# Chrome adds an extra focus for some reason - ok for now
expect(session.evaluate_script('window.capybara_formDateFiredEvents')).to eq(%w[focus input change])
end
end
describe '#fill_in with { clear: Array } fill_options' do
it 'should pass the array through to the element' do
# this is mainly for use with [[:control, 'a'], :backspace] - however since that is platform dependant I'm testing with something less useful
session.visit('/form')
session.fill_in('form_first_name',
with: 'Harry',
fill_options: { clear: [[:shift, 'abc'], :backspace] })
expect(session.find(:fillable_field, 'form_first_name').value).to eq('JohnABHarry')
end
end
describe '#fill_in with Emoji' do
it 'sends emojis' do
session.visit('/form')
session.fill_in('form_first_name', with: 'a๐cd๐ด ๐๐ฝ๐ต๐น e๐คพ๐ฝโโ๏ธf')
expect(session.find(:fillable_field, 'form_first_name').value).to eq('a๐cd๐ด ๐๐ฝ๐ต๐น e๐คพ๐ฝโโ๏ธf')
end
end
describe '#send_keys' do
it 'defaults to sending keys to the active_element' do
session.visit('/form')
expect(session.active_element).to match_selector(:css, 'body')
session.send_keys(:tab)
expect(session.active_element).to match_selector(:css, '[tabindex="1"]')
end
end
describe '#path' do
it 'returns xpath' do
# this is here because it is testing for an XPath that is specific to the algorithm used in the selenium driver
session.visit('/path')
element = session.find(:link, 'Second Link')
expect(element.path).to eq('/HTML/BODY[1]/DIV[2]/A[1]')
end
it 'handles namespaces in xhtml' do
pending "IE 11 doesn't handle all XPath querys (namespace-uri, etc)" if ie?(session)
session.visit '/with_namespace'
rect = session.find(:css, 'div svg rect:first-of-type')
expect(rect.path).to eq("/HTML/BODY[1]/DIV[1]/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg'][1]/*[local-name()='rect' and namespace-uri()='http://www.w3.org/2000/svg'][1]")
expect(session.find(:xpath, rect.path)).to eq rect
end
it 'handles default namespaces in html5' do
pending "IE 11 doesn't handle all XPath querys (namespace-uri, etc)" if ie?(session)
session.visit '/with_html5_svg'
rect = session.find(:css, 'div svg rect:first-of-type')
expect(rect.path).to eq("/HTML/BODY[1]/DIV[1]/*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg'][1]/*[local-name()='rect' and namespace-uri()='http://www.w3.org/2000/svg'][1]")
expect(session.find(:xpath, rect.path)).to eq rect
end
it 'handles case sensitive element names' do
pending "IE 11 doesn't handle all XPath querys (namespace-uri, etc)" if ie?(session)
session.visit '/with_namespace'
els = session.all(:css, 'div *', visible: :all)
expect { els.map(&:path) }.not_to raise_error
lg = session.find(:css, 'div linearGradient', visible: :all)
expect(session.find(:xpath, lg.path, visible: :all)).to eq lg
end
end
describe 'all with disappearing elements' do
it 'ignores stale elements in results' do
session.visit('/path')
elements = session.all(:link) { |_node| raise Selenium::WebDriver::Error::StaleElementReferenceError }
expect(elements.size).to eq 0
end
end
describe '#evaluate_script' do
it 'can return an element' do
session.visit('/form')
element = session.evaluate_script("document.getElementById('form_title')")
expect(element).to eq session.find(:id, 'form_title')
end
it 'returns a shadow root' do
session.visit('/with_shadow')
shadow = session.find(:css, '#shadow_host')
element = session.evaluate_script('arguments[0].shadowRoot', shadow)
expect(element).to be_instance_of(Capybara::Node::Element)
end
it 'can return arrays of nested elements' do
session.visit('/form')
elements = session.evaluate_script('document.querySelectorAll("#form_city option")')
expect(elements).to all(be_instance_of Capybara::Node::Element)
expect(elements).to eq session.find(:css, '#form_city').all(:css, 'option').to_a
end
it 'can return hashes with elements' do
session.visit('/form')
result = session.evaluate_script("{ a: document.getElementById('form_title'), b: {c: document.querySelectorAll('#form_city option')}}")
expect(result).to eq(
'a' => session.find(:id, 'form_title'),
'b' => {
'c' => session.find(:css, '#form_city').all(:css, 'option').to_a
}
)
end
describe '#evaluate_async_script' do
it 'will timeout if the script takes too long' do
skip 'safaridriver returns the wrong error type' if safari?(session)
session.visit('/with_js')
expect do
session.using_wait_time(1) do
session.evaluate_async_script('var cb = arguments[0]; setTimeout(function(){ cb(null) }, 3000)')
end
end.to raise_error Selenium::WebDriver::Error::ScriptTimeoutError
end
end
end
describe 'Element#inspect' do
it 'outputs obsolete elements' do
session.visit('/form')
el = session.find(:button, 'Click me!').click
expect(session).to have_no_button('Click me!')
allow(el).to receive(:synchronize)
expect(el.inspect).to eq 'Obsolete #<Capybara::Node::Element>'
expect(el).not_to have_received(:synchronize)
end
end
describe 'Element#click' do
it 'should handle fixed headers/footers' do
session.visit('/with_fixed_header_footer')
session.using_wait_time(2) do
session.find(:link, 'Go to root').click
end
expect(session).to have_current_path('/')
end
end
describe 'Capybara#Node#attach_file' do
it 'can attach a directory' do
pending "Geckodriver doesn't support uploading a directory" if firefox?(session)
pending "Selenium remote doesn't support transferring a directory" if remote?(session)
pending "Headless Chrome doesn't support directory upload - https://bugs.chromium.org/p/chromedriver/issues/detail?id=2521&q=directory%20upload&colspec=ID%20Status%20Pri%20Owner%20Summary" if chrome?(session) && chrome_lt?(110, session) && ENV.fetch('HEADLESS', nil)
pending "IE doesn't support uploading a directory" if ie?(session)
pending 'Chrome/chromedriver 73 breaks this' if chrome?(session) && chrome_gte?(73, session) && chrome_lt?(75, session)
session.visit('/form')
test_file_dir = File.expand_path('./fixtures', File.dirname(__FILE__))
session.attach_file('Directory Upload', test_file_dir)
session.click_button('Upload Multiple')
expect(session).to have_text('5 | ') # number of files
end
it 'can attach a relative file' do
pending 'Geckdoriver on windows requires alternate file separator which path expansion replaces' if Gem.win_platform? && firefox?(session)
session.visit('/form')
session.attach_file('Single Document', 'spec/fixtures/capybara.csv')
session.click_button('Upload Single')
expect(session).to have_text('Content-type: text/csv')
end
end
context 'Windows' do
it "can't close the primary window" do
expect do
session.current_window.close
end.to raise_error(ArgumentError, 'Not allowed to close the primary window')
end
end
# rubocop:disable RSpec/InstanceVariable
describe 'Capybara#disable_animation' do
context 'when set to `true`' do
before(:context) do # rubocop:disable RSpec/BeforeAfterAll
skip "Safari doesn't support multiple sessions" if safari?(session)
# NOTE: Although Capybara.SpecHelper.reset! sets Capybara.disable_animation to false,
# it doesn't affect any of these tests because the settings are applied per-session
Capybara.disable_animation = true
@animation_session = Capybara::Session.new(session.mode, TestApp.new)
end
it 'should add CSS to the <head> element' do
@animation_session.visit('with_animation')
expect(@animation_session).to have_selector(:css, 'head > style', text: 'transition: none', visible: :hidden)
end
it 'should disable CSS transitions' do
@animation_session.visit('with_animation')
@animation_session.click_link('transition me away')
expect(@animation_session).to have_no_link('transition me away', wait: 0.5)
end
it 'should disable CSS animations (set to 0s)' do
@animation_session.visit('with_animation')
sleep 1
@animation_session.click_link('animate me away')
expect(@animation_session).to have_no_link('animate me away', wait: 0.5)
end
it 'should disable CSS animations on pseudo elements (set to 0s)' do
@animation_session.visit('with_animation')
sleep 1
@animation_session.find_link('animate me away').right_click
expect(@animation_session).to have_content('Animation Ended', wait: 0.1)
end
it 'should scroll the page instantly', requires: [:js] do
@animation_session.visit('with_animation')
scroll_y = @animation_session.evaluate_script(<<~JS)
(function(){
window.scrollTo(0,500);
return window.scrollY;
})()
JS
expect(scroll_y).to eq 500
end
it 'should scroll the page instantly without jquery animation', requires: [:js] do
@animation_session.visit('with_jquery_animation')
@animation_session.click_link('scroll top 500')
scroll_y = @animation_session.evaluate_script('window.scrollY')
expect(scroll_y).to eq 500
end
end
context 'when set to `false`' do
before(:context) do # rubocop:disable RSpec/BeforeAfterAll
skip "Safari doesn't support multiple sessions" if safari?(session)
# NOTE: Although Capybara.SpecHelper.reset! sets Capybara.disable_animation to false,
# it doesn't affect any of these tests because the settings are applied per-session
Capybara.disable_animation = false
@animation_session = Capybara::Session.new(session.mode, TestApp.new)
end
it 'should scroll the page with a smooth animation', requires: [:js] do
@animation_session.visit('with_animation')
scroll_y = @animation_session.evaluate_script(<<~JS)
(function(){
window.scrollTo(0,500);
return window.scrollY;
})()
JS
# measured over 0.5 seconds: 0, 75, 282, 478, 500
expect(scroll_y).to be < 500
end
it 'should scroll the page with jquery animation', requires: [:js] do
@animation_session.visit('with_jquery_animation')
@animation_session.click_link('scroll top 500')
scroll_y = @animation_session.evaluate_script('window.scrollY')
expect(scroll_y).to be < 500
end
end
context 'if we pass in css that matches elements' do
before(:context) do # rubocop:disable RSpec/BeforeAfterAll
skip "safaridriver doesn't support multiple sessions" if safari?(session)
# NOTE: Although Capybara.SpecHelper.reset! sets Capybara.disable_animation to false,
# it doesn't affect any of these tests because the settings are applied per-session
Capybara.disable_animation = '#with_animation a'
@animation_session_with_matching_css = Capybara::Session.new(session.mode, TestApp.new)
end
it 'should disable CSS transitions' do
@animation_session_with_matching_css.visit('with_animation')
sleep 1
@animation_session_with_matching_css.click_link('transition me away')
expect(@animation_session_with_matching_css).to have_no_link('transition me away', wait: 0.5)
end
it 'should disable CSS animations' do
@animation_session_with_matching_css.visit('with_animation')
sleep 1
@animation_session_with_matching_css.click_link('animate me away')
expect(@animation_session_with_matching_css).to have_no_link('animate me away', wait: 0.5)
end
end
context 'if we pass in css that does not match elements' do
before(:context) do # rubocop:disable RSpec/BeforeAfterAll
skip "Safari doesn't support multiple sessions" if safari?(session)
# NOTE: Although Capybara.SpecHelper.reset! sets Capybara.disable_animation to false,
# it doesn't affect any of these tests because the settings are applied per-session
Capybara.disable_animation = '.this-class-matches-nothing'
@animation_session_without_matching_css = Capybara::Session.new(session.mode, TestApp.new)
end
it 'should not disable CSS transitions' do
@animation_session_without_matching_css.visit('with_animation')
sleep 1
@animation_session_without_matching_css.click_link('transition me away')
sleep 0.5 # Wait long enough for click to have been processed
expect(@animation_session_without_matching_css).to have_link('transition me away', wait: false)
expect(@animation_session_without_matching_css).to have_no_link('transition me away', wait: 5)
end
it 'should not disable CSS animations' do
@animation_session_without_matching_css.visit('with_animation')
sleep 1
@animation_session_without_matching_css.click_link('animate me away')
sleep 0.5 # Wait long enough for click to have been processed
expect(@animation_session_without_matching_css).to have_link('animate me away', wait: false)
expect(@animation_session_without_matching_css).to have_no_link('animate me away', wait: 5)
end
end
end
# rubocop:enable RSpec/InstanceVariable
describe ':element selector' do
it 'can find html5 svg elements' do
session.visit('with_html5_svg')
expect(session).to have_selector(:element, :svg)
expect(session).to have_selector(:element, :rect, visible: :visible)
expect(session).to have_selector(:element, :circle)
expect(session).to have_selector(:element, :linearGradient, visible: :all)
end
it 'can query attributes with strange characters' do
session.visit('/form')
expect(session).to have_selector(:element, '{custom}': true)
expect(session).to have_selector(:element, '{custom}': 'abcdef')
end
end
describe 'with react' do
context 'controlled components' do
it 'can set and clear a text field' do
skip "This test doesn't support older browsers" if ie?(session)
session.visit 'react'
session.fill_in('Name:', with: 'abc')
session.accept_prompt 'A name was submitted: abc' do
session.click_button('Submit')
end
session.fill_in('Name:', with: '')
session.accept_prompt(/A name was submitted: $/) do
session.click_button('Submit')
end
end
it 'works with rapid fill' do
skip "This test doesn't support older browsers" if ie?(session)
session.visit 'react'
long_string = (0...60).map { |i| ((i % 26) + 65).chr }.join
session.fill_in('Name:', with: long_string)
session.accept_prompt "A name was submitted: #{long_string}" do
session.click_button('Submit')
end
end
end
end
end
def headless_or_remote?
!ENV['HEADLESS'].nil? || session.driver.options[:browser] == :remote
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec/shared_spec_matchers.rb | spec/rspec/shared_spec_matchers.rb | # frozen_string_literal: true
require 'spec_helper'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require 'benchmark'
# rubocop:disable RSpec/ExpectActual
RSpec.shared_examples Capybara::RSpecMatchers do |session, _mode|
include Capybara::DSL
include Capybara::RSpecMatchers
describe 'have_css matcher' do
it 'gives proper description' do
expect(have_css('h1').description).to eq('have visible css "h1"')
end
context 'on a string' do
context 'with should' do
it 'passes if has_css? returns true' do
expect('<h1>Text</h1>').to have_css('h1')
end
it 'fails if has_css? returns false' do
expect do
expect('<h1>Text</h1>').to have_css('h2')
end.to raise_error(/expected to find css "h2" but there were no matches/)
end
it 'passes if matched node count equals expected count' do
expect('<h1>Text</h1>').to have_css('h1', count: 1)
end
it 'fails if matched node count does not equal expected count' do
expect do
expect('<h1>Text</h1>').to have_css('h1', count: 2)
end.to raise_error('expected to find visible css "h1" 2 times, found 1 match: "Text"')
end
it 'fails if matched node count is less than expected minimum count' do
expect do
expect('<h1>Text</h1>').to have_css('p', minimum: 1)
end.to raise_error('expected to find css "p" at least 1 time but there were no matches')
end
it 'fails if matched node count is more than expected maximum count' do
expect do
expect('<h1>Text</h1><h1>Text</h1><h1>Text</h1>').to have_css('h1', maximum: 2)
end.to raise_error('expected to find visible css "h1" at most 2 times, found 3 matches: "Text", "Text", "Text"')
end
it 'fails if matched node count does not belong to expected range' do
expect do
expect('<h1>Text</h1>').to have_css('h1', between: 2..3)
end.to raise_error('expected to find visible css "h1" between 2 and 3 times, found 1 match: "Text"')
end
end
context 'with should_not' do
it 'passes if has_no_css? returns true' do
expect('<h1>Text</h1>').not_to have_css('h2')
end
it 'fails if has_no_css? returns false' do
expect do
expect('<h1>Text</h1>').not_to have_css('h1')
end.to raise_error(/expected not to find visible css "h1"/)
end
it 'passes if matched node count does not equal expected count' do
expect('<h1>Text</h1>').not_to have_css('h1', count: 2)
end
it 'fails if matched node count equals expected count' do
expect do
expect('<h1>Text</h1>').not_to have_css('h1', count: 1)
end.to raise_error(/expected not to find visible css "h1"/)
end
end
it 'supports compounding' do
expect('<h1>Text</h1><h2>Text</h2>').to have_css('h1').and have_css('h2')
expect('<h1>Text</h1><h2>Text</h2>').to have_css('h3').or have_css('h1')
expect('<h1>Text</h1><h2>Text</h2>').to have_no_css('h4').and have_css('h2')
expect('<h1>Text</h1><h2>Text</h2>').to have_no_css('h2').or have_css('h1')
end
end
context 'on a page or node' do
before do
session.visit('/with_html')
end
context 'with should' do
it 'passes if has_css? returns true' do
expect(session).to have_css('h1')
end
it 'fails if has_css? returns false' do
expect do
expect(session).to have_css('h1#doesnotexist')
end.to raise_error(/expected to find css "h1#doesnotexist" but there were no matches/)
end
end
context 'with should_not' do
it 'passes if has_no_css? returns true' do
expect(session).not_to have_css('h1#doesnotexist')
end
it 'fails if has_no_css? returns false' do
expect do
expect(session).not_to have_css('h1')
end.to raise_error(/expected not to find visible css "h1"/)
end
end
end
end
describe 'have_xpath matcher' do
it 'gives proper description' do
expect(have_xpath('//h1').description).to eq('have visible xpath "//h1"')
end
context 'on a string' do
context 'with should' do
it 'passes if has_xpath? returns true' do
expect('<h1>Text</h1>').to have_xpath('//h1')
end
it 'fails if has_xpath? returns false' do
expect do
expect('<h1>Text</h1>').to have_xpath('//h2')
end.to raise_error(%r{expected to find xpath "//h2" but there were no matches})
end
end
context 'with should_not' do
it 'passes if has_no_xpath? returns true' do
expect('<h1>Text</h1>').not_to have_xpath('//h2')
end
it 'fails if has_no_xpath? returns false' do
expect do
expect('<h1>Text</h1>').not_to have_xpath('//h1')
end.to raise_error(%r{expected not to find visible xpath "//h1"})
end
end
it 'supports compounding' do
expect('<h1>Text</h1><h2>Text</h2>').to have_xpath('//h1').and have_xpath('//h2')
expect('<h1>Text</h1><h2>Text</h2>').to have_xpath('//h3').or have_xpath('//h1')
expect('<h1>Text</h1><h2>Text</h2>').to have_no_xpath('//h4').and have_xpath('//h1')
expect('<h1>Text</h1><h2>Text</h2>').to have_no_xpath('//h4').or have_xpath('//h4')
end
end
context 'on a page or node' do
before do
session.visit('/with_html')
end
context 'with should' do
it 'passes if has_xpath? returns true' do
expect(session).to have_xpath('//h1')
end
it 'fails if has_xpath? returns false' do
expect do
expect(session).to have_xpath("//h1[@id='doesnotexist']")
end.to raise_error(%r{expected to find xpath "//h1\[@id='doesnotexist'\]" but there were no matches})
end
end
context 'with should_not' do
it 'passes if has_no_xpath? returns true' do
expect(session).not_to have_xpath('//h1[@id="doesnotexist"]')
end
it 'fails if has_no_xpath? returns false' do
expect do
expect(session).not_to have_xpath('//h1')
end.to raise_error(%r{expected not to find visible xpath "//h1"})
end
end
end
end
describe 'have_selector matcher' do
it 'gives proper description' do
matcher = have_selector('//h1')
expect('<h1>Text</h1>').to matcher
expect(matcher.description).to eq('have visible xpath "//h1"')
end
context 'on a string' do
context 'with should' do
it 'passes if has_selector? returns true' do
expect('<h1>Text</h1>').to have_selector('//h1')
end
it 'fails if has_selector? returns false' do
expect do
expect('<h1>Text</h1>').to have_selector('//h2')
end.to raise_error(%r{expected to find xpath "//h2" but there were no matches})
end
end
context 'with should_not' do
it 'passes if has_no_selector? returns true' do
expect('<h1>Text</h1>').not_to have_selector(:css, 'h2')
end
it 'fails if has_no_selector? returns false' do
expect do
expect('<h1>Text</h1>').not_to have_selector(:css, 'h1')
end.to raise_error(/expected not to find visible css "h1"/)
end
end
end
context 'on a page or node' do
before do
session.visit('/with_html')
end
context 'with should' do
it 'passes if has_selector? returns true' do
expect(session).to have_selector('//h1', text: 'test')
end
it 'fails if has_selector? returns false' do
expect do
expect(session).to have_selector("//h1[@id='doesnotexist']")
end.to raise_error(%r{expected to find xpath "//h1\[@id='doesnotexist'\]" but there were no matches})
end
it 'includes text in error message' do
expect do
expect(session).to have_selector('//h1', text: 'wrong text')
end.to raise_error(%r{expected to find visible xpath "//h1" with text "wrong text" but there were no matches})
end
end
context 'with should_not' do
it 'passes if has_no_css? returns true' do
expect(session).not_to have_selector(:css, 'h1#doesnotexist')
end
it 'fails if has_no_selector? returns false' do
expect do
expect(session).not_to have_selector(:css, 'h1', text: 'test')
end.to raise_error(/expected not to find visible css "h1" with text "test"/)
end
end
end
it 'supports compounding' do
expect('<h1>Text</h1><h2>Text</h2>').to have_selector('//h1').and have_selector('//h2')
expect('<h1>Text</h1><h2>Text</h2>').to have_selector('//h3').or have_selector('//h1')
expect('<h1>Text</h1><h2>Text</h2>').to have_no_selector('//h3').and have_selector('//h1')
end
end
describe 'have_content matcher' do
it 'gives proper description' do
expect(have_content('Text').description).to eq('have text "Text"')
end
context 'on a string' do
context 'with should' do
it 'passes if has_content? returns true' do
expect('<h1>Text</h1>').to have_content('Text')
end
it 'passes if has_content? returns true using regexp' do
expect('<h1>Text</h1>').to have_content(/ext/)
end
it 'fails if has_content? returns false' do
expect do
expect('<h1>Text</h1>').to have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "Text"/)
end
end
context 'with should_not' do
it 'passes if has_no_content? returns true' do
expect('<h1>Text</h1>').not_to have_content('No such Text')
end
it 'passes because escapes any characters that would have special meaning in a regexp' do
expect('<h1>Text</h1>').not_to have_content('.')
end
it 'fails if has_no_content? returns false' do
expect do
expect('<h1>Text</h1>').not_to have_content('Text')
end.to raise_error(/expected not to find text "Text" in "Text"/)
end
end
end
context 'on a page or node' do
before do
session.visit('/with_html')
end
context 'with should' do
it 'passes if has_content? returns true' do
expect(session).to have_content('This is a test')
end
it 'passes if has_content? returns true using regexp' do
expect(session).to have_content(/test/)
end
it 'fails if has_content? returns false' do
expect do
expect(session).to have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
context 'with default selector CSS' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'fails if has_content? returns false' do
expect do
expect(session).to have_content('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
end
end
context 'with should_not' do
it 'passes if has_no_content? returns true' do
expect(session).not_to have_content('No such Text')
end
it 'fails if has_no_content? returns false' do
expect do
expect(session).not_to have_content('This is a test')
end.to raise_error(/expected not to find text "This is a test"/)
end
it 'not_to have_content behaves the same as to have_no_content' do
Capybara.using_wait_time(5) do
expect(session).to have_content('This is a test')
start = Time.now
expect(session).to have_no_content('No such Text')
to_time = Time.now
expect(session).not_to have_content('No such Text')
not_to_time = Time.now
expect(not_to_time - to_time).to be_within(0.5).of(to_time - start)
end
end
end
end
it 'supports compounding' do
expect('<h1>Text</h1><h2>And</h2>').to have_content('Text').and have_content('And')
expect('<h1>Text</h1><h2>Or</h2>').to have_content('XYZ').or have_content('Or')
expect('<h1>Text</h1><h2>Or</h2>').to have_no_content('XYZ').and have_content('Or')
end
end
describe 'have_text matcher' do
it 'gives proper description' do
expect(have_text('Text').description).to eq('have text "Text"')
end
context 'on a string' do
context 'with should' do
it 'passes if text contains given string' do
expect('<h1>Text</h1>').to have_text('Text')
end
it 'passes if text matches given regexp' do
expect('<h1>Text</h1>').to have_text(/ext/)
end
it "fails if text doesn't contain given string" do
expect do
expect('<h1>Text</h1>').to have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "Text"/)
end
it "fails if text doesn't match given regexp" do
expect do
expect('<h1>Text</h1>').to have_text(/No such Text/)
end.to raise_error('expected to find text matching /No such Text/ in "Text"')
end
it 'casts Integer to string' do
expect do
expect('<h1>Text</h1>').to have_text(3)
end.to raise_error(/expected to find text "3" in "Text"/)
end
it 'fails if matched text count does not equal to expected count' do
expect do
expect('<h1>Text</h1>').to have_text('Text', count: 2)
end.to raise_error('expected to find text "Text" 2 times but found 1 time in "Text"')
end
it 'fails if matched text count is less than expected minimum count' do
expect do
expect('<h1>Text</h1>').to have_text('Lorem', minimum: 1)
end.to raise_error('expected to find text "Lorem" at least 1 time but found 0 times in "Text"')
end
it 'fails if matched text count is more than expected maximum count' do
expect do
expect('<h1>Text TextText</h1>').to have_text('Text', maximum: 2)
end.to raise_error('expected to find text "Text" at most 2 times but found 3 times in "Text TextText"')
end
it 'fails if matched text count does not belong to expected range' do
expect do
expect('<h1>Text</h1>').to have_text('Text', between: 2..3)
end.to raise_error('expected to find text "Text" between 2 and 3 times but found 1 time in "Text"')
end
end
context 'with should_not' do
it "passes if text doesn't contain a string" do
expect('<h1>Text</h1>').not_to have_text('No such Text')
end
it 'passes because escapes any characters that would have special meaning in a regexp' do
expect('<h1>Text</h1>').not_to have_text('.')
end
it 'fails if text contains a string' do
expect do
expect('<h1>Text</h1>').not_to have_text('Text')
end.to raise_error(/expected not to find text "Text" in "Text"/)
end
end
end
context 'on a page or node' do
before do
session.visit('/with_html')
end
context 'with should' do
it 'passes if has_text? returns true' do
expect(session).to have_text('This is a test')
end
it 'passes if has_text? returns true using regexp' do
expect(session).to have_text(/test/)
end
it 'can check for all text' do
expect(session).to have_text(:all, 'Some of this text is hidden!')
end
it 'can check for visible text' do
expect(session).to have_text(:visible, 'Some of this text is')
expect(session).not_to have_text(:visible, 'Some of this text is hidden!')
end
it 'fails if has_text? returns false' do
expect do
expect(session).to have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
context 'with default selector CSS' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'fails if has_text? returns false' do
expect do
expect(session).to have_text('No such Text')
end.to raise_error(/expected to find text "No such Text" in "(.*)This is a test(.*)"/)
end
end
end
context 'with should_not' do
it 'passes if has_no_text? returns true' do
expect(session).not_to have_text('No such Text')
end
it 'fails if has_no_text? returns false' do
expect do
expect(session).not_to have_text('This is a test')
end.to raise_error(/expected not to find text "This is a test"/)
end
end
end
it 'supports compounding' do
expect('<h1>Text</h1><h2>And</h2>').to have_text('Text').and have_text('And')
expect('<h1>Text</h1><h2>Or</h2>').to have_text('Not here').or have_text('Or')
end
end
describe 'have_element matcher' do
let(:html) { '<img src="/img.jpg" alt="a JPEG"><img src="/img.png" alt="a PNG">' }
it 'gives proper description' do
expect(have_element('img').description).to eq('have visible element "img"')
end
it 'passes if there is such a element' do
expect(html).to have_element('img', src: '/img.jpg')
end
it 'fails if there is no such element' do
expect do
expect(html).to have_element('photo')
end.to raise_error(/expected to find element "photo"/)
end
it 'supports compounding' do
expect(html).to have_element('img', alt: 'a JPEG').and have_element('img', src: '/img.png')
expect(html).to have_element('photo').or have_element('img', src: '/img.jpg')
expect(html).to have_no_element('photo').and have_element('img', alt: 'a PNG')
end
end
describe 'have_link matcher' do
let(:html) { '<a href="#">Just a link</a><a href="#">Another link</a>' }
it 'gives proper description' do
expect(have_link('Just a link').description).to eq('have visible link "Just a link"')
end
it 'passes if there is such a link' do
expect(html).to have_link('Just a link')
end
it 'fails if there is no such link' do
expect do
expect(html).to have_link('No such Link')
end.to raise_error(/expected to find link "No such Link"/)
end
it 'supports compounding' do
expect(html).to have_link('Just a link').and have_link('Another link')
expect(html).to have_link('Not a link').or have_link('Another link')
expect(html).to have_no_link('Not a link').and have_link('Another link')
end
end
describe 'have_title matcher' do
it 'gives proper description' do
expect(have_title('Just a title').description).to eq('have title "Just a title"')
end
context 'on a string' do
let(:html) { '<title>Just a title</title>' }
it 'passes if there is such a title' do
expect(html).to have_title('Just a title')
end
it 'fails if there is no such title' do
expect do
expect(html).to have_title('No such title')
end.to raise_error('expected "Just a title" to include "No such title"')
end
it "fails if title doesn't match regexp" do
expect do
expect(html).to have_title(/[[:upper:]]+[[:lower:]]+l{2}o/)
end.to raise_error('expected "Just a title" to match /[[:upper:]]+[[:lower:]]+l{2}o/')
end
end
context 'on a page or node' do
it 'passes if there is such a title' do
session.visit('/with_js')
expect(session).to have_title('with_js')
end
it 'fails if there is no such title' do
session.visit('/with_js')
expect do
expect(session).to have_title('No such title')
end.to raise_error(/ to include "No such title"/)
end
context 'with wait' do
before do
session.visit('/with_js')
end
it 'waits if wait time is more than timeout' do
session.click_link('Change title')
session.using_wait_time 0 do
expect(session).to have_title('changed title', wait: 2)
end
end
it "doesn't wait if wait time is less than timeout" do
session.click_link('Change title')
session.using_wait_time 3 do
expect(session).not_to have_title('changed title', wait: 0)
end
end
end
end
it 'supports compounding' do
expect('<title>I compound</title>').to have_title('I dont compound').or have_title('I compound')
end
end
describe 'have_current_path matcher' do
it 'gives proper description' do
expect(have_current_path('http://www.example.com').description).to eq('have current path "http://www.example.com"')
end
context 'on a page or node' do
it 'passes if there is such a current path' do
session.visit('/with_js')
expect(session).to have_current_path('/with_js')
end
it 'fails if there is no such current_path' do
visit('/with_js')
expect do
expect(session).to have_current_path('/not_with_js')
end.to raise_error(%r{to equal "/not_with_js"})
end
context 'with wait' do
before do
session.visit('/with_js')
end
it 'waits if wait time is more than timeout' do
session.click_link('Change page')
session.using_wait_time 0 do
expect(session).to have_current_path('/with_html', wait: 2)
end
end
it "doesn't wait if wait time is less than timeout" do
session.click_link('Change page')
session.using_wait_time 0 do
expect(session).not_to have_current_path('/with_html')
end
end
end
end
it 'supports compounding' do
session.visit('/with_html')
expect(session).to have_current_path('/not_with_html').or have_current_path('/with_html')
end
end
describe 'have_button matcher' do
let(:html) { '<button>A button</button><input type="submit" value="Another button"/>' }
it 'gives proper description with no options' do
expect(have_button('A button').description).to eq('have visible button "A button" that is not disabled')
end
it 'gives proper description with disabled :any option' do
expect(have_button('A button', disabled: :all).description).to eq('have visible button "A button"')
end
it 'passes if there is such a button' do
expect(html).to have_button('A button')
end
it 'fails if there is no such button' do
expect do
expect(html).to have_button('No such Button')
end.to raise_error(/expected to find button "No such Button"/)
end
it 'supports compounding' do
expect(html).to have_button('Not this button').or have_button('A button')
end
end
describe 'have_field matcher' do
let(:html) { '<p><label>Text field<input type="text" value="some value"/></label></p>' }
it 'gives proper description' do
expect(have_field('Text field').description).to eq('have visible field "Text field" that is not disabled')
end
it 'gives proper description for a given value' do
expect(have_field('Text field', with: 'some value').description).to eq('have visible field "Text field" that is not disabled with value "some value"')
end
it 'passes if there is such a field' do
expect(html).to have_field('Text field')
end
it 'passes if there is such a field with value' do
expect(html).to have_field('Text field', with: 'some value')
end
it 'fails if there is no such field' do
expect do
expect(html).to have_field('No such Field')
end.to raise_error(/expected to find field "No such Field"/)
end
it 'fails if there is such field but with false value' do
expect do
expect(html).to have_field('Text field', with: 'false value')
end.to raise_error(/expected to find visible field "Text field"/)
end
it 'treats a given value as a string' do
foo = Class.new do
def to_s
'some value'
end
end
expect(html).to have_field('Text field', with: foo.new)
end
it 'supports compounding' do
expect(html).to have_field('Not this one').or have_field('Text field')
end
end
describe 'have_checked_field matcher' do
let(:html) do
'<label>it is checked<input type="checkbox" checked="checked"/></label>
<label>unchecked field<input type="checkbox"/></label>'
end
it 'gives proper description' do
expect(have_checked_field('it is checked').description).to eq('have visible field "it is checked" that is not disabled that is checked')
end
context 'with should' do
it 'passes if there is such a field and it is checked' do
expect(html).to have_checked_field('it is checked')
end
it 'fails if there is such a field but it is not checked' do
expect do
expect(html).to have_checked_field('unchecked field')
end.to raise_error(/expected to find visible field "unchecked field"/)
end
it 'fails if there is no such field' do
expect do
expect(html).to have_checked_field('no such field')
end.to raise_error(/expected to find field "no such field"/)
end
end
context 'with should not' do
it 'fails if there is such a field and it is checked' do
expect do
expect(html).not_to have_checked_field('it is checked')
end.to raise_error(/expected not to find visible field "it is checked"/)
end
it 'passes if there is such a field but it is not checked' do
expect(html).not_to have_checked_field('unchecked field')
end
it 'passes if there is no such field' do
expect(html).not_to have_checked_field('no such field')
end
end
it 'supports compounding' do
expect(html).to have_checked_field('not this one').or have_checked_field('it is checked')
end
end
describe 'have_unchecked_field matcher' do
let(:html) do
'<label>it is checked<input type="checkbox" checked="checked"/></label>
<label>unchecked field<input type="checkbox"/></label>'
end
it 'gives proper description' do
expect(have_unchecked_field('unchecked field').description).to eq('have visible field "unchecked field" that is not disabled that is not checked')
end
context 'with should' do
it 'passes if there is such a field and it is not checked' do
expect(html).to have_unchecked_field('unchecked field')
end
it 'fails if there is such a field but it is checked' do
expect do
expect(html).to have_unchecked_field('it is checked')
end.to raise_error(/expected to find visible field "it is checked"/)
end
it 'fails if there is no such field' do
expect do
expect(html).to have_unchecked_field('no such field')
end.to raise_error(/expected to find field "no such field"/)
end
end
context 'with should not' do
it 'fails if there is such a field and it is not checked' do
expect do
expect(html).not_to have_unchecked_field('unchecked field')
end.to raise_error(/expected not to find visible field "unchecked field"/)
end
it 'passes if there is such a field but it is checked' do
expect(html).not_to have_unchecked_field('it is checked')
end
it 'passes if there is no such field' do
expect(html).not_to have_unchecked_field('no such field')
end
end
it 'supports compounding' do
expect(html).to have_unchecked_field('it is checked').or have_unchecked_field('unchecked field')
end
end
describe 'have_select matcher' do
let(:html) { '<label>Select Box<select></select></label>' }
it 'gives proper description' do
expect(have_select('Select Box').description).to eq('have visible select box "Select Box" that is not disabled')
end
it 'gives proper description for a given selected value' do
expect(have_select('Select Box', selected: 'some value').description).to eq('have visible select box "Select Box" that is not disabled with "some value" selected')
end
it 'passes if there is such a select' do
expect(html).to have_select('Select Box')
end
it 'fails if there is no such select' do
expect do
expect(html).to have_select('No such Select box')
end.to raise_error(/expected to find select box "No such Select box"/)
end
it 'supports compounding' do
expect(html).to have_select('Not this one').or have_select('Select Box')
end
end
describe 'have_table matcher' do
let(:html) { '<table><caption>Lovely table</caption></table>' }
it 'gives proper description' do
expect(have_table('Lovely table').description).to eq('have visible table "Lovely table"')
expect(have_table('Lovely table', caption: 'my caption').description).to eq('have visible table "Lovely table" with caption "my caption"')
end
it 'gives proper description when :visible option passed' do
expect(have_table('Lovely table', visible: true).description).to eq('have visible table "Lovely table"') # rubocop:disable Capybara/VisibilityMatcher
expect(have_table('Lovely table', visible: :hidden).description).to eq('have non-visible table "Lovely table"')
expect(have_table('Lovely table', visible: :all).description).to eq('have table "Lovely table"')
expect(have_table('Lovely table', visible: false).description).to eq('have table "Lovely table"') # rubocop:disable Capybara/VisibilityMatcher
end
it 'passes if there is such a table' do
expect(html).to have_table('Lovely table')
end
it 'fails if there is no such table' do
expect do
expect(html).to have_table('No such Table')
end.to raise_error(/expected to find table "No such Table"/)
end
it 'supports compounding' do
expect(html).to have_table('nope').or have_table('Lovely table')
end
end
context 'compounding timing' do
let(:session) { session }
let(:el) { session.find(:css, '#reload-me') }
before do
session.visit('/with_js')
end
describe '#and' do
it "should run 'concurrently'" do
session.using_wait_time(2) do
matcher = have_text('this is not there').and have_text('neither is this')
expect(Benchmark.realtime do
expect do
expect(el).to matcher
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end).to be_between(2, 3)
end
end
it "should run 'concurrently' and retry" do
session.click_link('reload-link')
session.using_wait_time(2) do
expect(Benchmark.realtime do
expect do
expect(el).to have_text('waiting to be reloaded').and(have_text('has been reloaded'))
end.to raise_error RSpec::Expectations::ExpectationNotMetError, /expected to find text "waiting to be reloaded" in "has been reloaded"/
end).to be_between(2, 3)
end
end
it 'should ignore :wait options' do
session.using_wait_time(2) do
matcher = have_text('this is not there', wait: 5).and have_text('neither is this', wait: 6)
expect(Benchmark.realtime do
expect do
expect(el).to matcher
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end).to be_between(2, 3)
end
end
it 'should work on the session' do
session.using_wait_time(2) do
session.click_link('reload-link')
expect(session).to have_selector(:css, 'h1', text: 'FooBar').and have_text('has been reloaded')
end
end
end
describe '#and_then' do
it 'should run sequentially' do
session.click_link('reload-link')
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.