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
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/opal/promisev2/test_then.rb
test/opal/promisev2/test_then.rb
require 'test/unit' require 'promise/v2' class TestPromiseThen < Test::Unit::TestCase def test_calls_the_block_when_the_promise_has_already_been_resolved x = 42 PromiseV2.value(23) .then { |v| x = v } .always { assert_equal(x, 23) } end def test_calls_the_block_when_the_promise_is_resolved a = PromiseV2.new x = 42 p = a.then { |v| x = v } a.resolve(23) p.always { assert_equal(x, 23) } end def test_works_with_multiple_chains x = 42 PromiseV2.value(2) .then { |v| v * 2 } .then { |v| v * 4 } .then { |v| x = v } .always { assert_equal(x, 16) } end def test_works_when_a_block_returns_a_promise a = PromiseV2.new b = PromiseV2.new x = 42 p = a.then { b }.then { |v| x = v } a.resolve(42) b.resolve(23) p.always { assert_equal(x, 23) } end def test_sends_raised_exceptions_as_rejections x = nil PromiseV2.value(2) .then { raise "hue" } .rescue { |v| x = v } .always { assert_equal(x.class, RuntimeError) } end def test_sends_raised_exceptions_inside_rescue_blocks_as_next_errors x = nil PromiseV2.value(2) .then { raise "hue" } .rescue { raise "omg" } .rescue { |v| x = v } .always { assert_equal(x.class, RuntimeError) } end def test_allows_then_to_be_called_multiple_times pr = PromiseV2.value(2) x = 1 ps = [] ps << pr.then { x += 1 } ps << pr.then { x += 1 } PromiseV2.when(ps).always { assert_equal(x, 3) } end def test_raises_with_thenB_if_a_promise_has_already_been_chained pr = PromiseV2.new pr.then! {} assert_raise(ArgumentError) { pr.then! {} } end def test_should_pass_a_delayed_falsy_value pr = PromiseV2.new.resolve(5).then { nil } pr.always do |value| assert_equal(value, nil) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/opal/promisev2/test_always.rb
test/opal/promisev2/test_always.rb
require 'test/unit' require 'promise/v2' class TestPromiseAlways < Test::Unit::TestCase def test_calls_the_block_when_it_was_resolved x = 42 PromiseV2.value(23) .then { |v| x = v } .always { |v| x = 2 } .then { assert_equal(x, 2) } end def test_calls_the_block_when_it_was_rejected x = 42 PromiseV2.error(23) .rescue { |v| x = v } .always { |v| x = 2 } .always { assert_equal(x, 2) } end def test_acts_as_resolved x = 42 PromiseV2.error(23) .rescue { |v| x = v } .always { x = 2 } .then { x = 3 } .always { assert_equal(x, 3) } end def test_can_be_called_multiple_times_on_resolved_promises p = PromiseV2.value(2) x = 1 ps = [] ps << p.then { x += 1 } ps << p.fail { x += 2 } ps << p.always { x += 3 } PromiseV2.when(ps).always do assert_equal(x, 5) end end def test_can_be_called_multiple_times_on_rejected_promises p = PromiseV2.error(2) x = 1 ps = [] ps << p.then { x += 1 }.fail{} ps << p.fail { x += 2 } ps << p.always { x += 3 }.fail{} PromiseV2.when(ps).then do assert_equal(x, 6) end end def test_raises_with_alwaysB_if_a_promise_has_already_been_chained p = PromiseV2.new p.then! {} assert_raise(ArgumentError) { p.always! {} } end def test_gets_the_value_from_the_previous_successful_block PromiseV2.value(23) .then { 123 } .rescue { 234 } .always { |v| assert_equal(123, v) } end def test_gets_the_value_from_the_previous_rescued_block PromiseV2.reject(23) .then { 123 } .rescue { 234 } .always { |v| assert_equal(234, v) } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/opal/promisev2/test_value.rb
test/opal/promisev2/test_value.rb
require 'test/unit' require 'promise/v2' class TestPromiseValue < Test::Unit::TestCase def test_resolves_the_promise_with_the_given_value assert_equal(PromiseV2.value(23).value, 23) end def test_marks_the_promise_as_realized assert_equal(PromiseV2.value(23).realized?, true) end def test_marks_the_promise_as_resolved assert_equal(PromiseV2.value(23).resolved?, true) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_io.rb
test/nodejs/test_io.rb
# Copied from cruby and modified to skip unsupported syntaxes require 'test/unit' require 'nodejs' require 'nodejs/io' class TestNodejsIO < Test::Unit::TestCase def test_binread File.write('tmp/foo', 'bar') assert_equal("bar", IO.binread('tmp/foo')) end def test_binread_noexistent_should_raise_io_error assert_raise IOError do IO.binread('tmp/nonexistent') end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_await.rb
test/nodejs/test_await.rb
# frozen_string_literal: true # await: true require "test/unit" class TestAwait < Test::Unit::TestCase stdheader = <<~RUBY # await: true require "await" RUBY autoawaitheader = <<~RUBY # await: *await* require "await" RUBY tests = { test_await_in_top: [<<~RUBY, 6], #{stdheader} $taval = 5 sleep(0.001).__await__ $taval = 6 RUBY test_await_in_method: [<<~RUBY, 7], #{stdheader} $taval = 5 def xx_taim sleep(0.001).__await__ $taval = 7 end xx_taim.__await__ RUBY test_await_in_block: [<<~RUBY, 0], #{stdheader} $taval = 5 xx_taib = proc do sleep(0.001).__await__ $taval = 0 end xx_taib.().__await__ RUBY test_await_in_instance_method: [<<~RUBY, 3], #{stdheader} $taval = 5 class XXTaiim def xx_taiim sleep(0.001).__await__ $taval = 3 end end XXTaiim.new.xx_taiim.__await__ RUBY test_await_in_class_method: [<<~RUBY, 4], #{stdheader} $taval = 5 class XXTaicm def self.xx_taicm sleep(0.001).__await__ $taval = 4 end end XXTaicm.xx_taicm.__await__ RUBY test_await_on_promise: [<<~RUBY, 8], #{stdheader} $taval = PromiseV2.value(8).__await__ RUBY test_await_in_while: [<<~RUBY, 9], #{stdheader} $taval = 5 begin sleep(0.001).__await__ $taval = 9 end while false RUBY test_await_in_while_expr: [<<~RUBY, -9], #{stdheader} $taval = 5 x = if true begin sleep(0.001).__await__ $taval = -9 end while false end RUBY test_await_in_case: [<<~RUBY, 88], #{stdheader} $taval = 5 case true when true sleep(0.001).__await__ $taval = 88 end RUBY test_await_in_case_expr: [<<~RUBY, 99], #{stdheader} $taval = 5 x = case true when true sleep(0.001).__await__ $taval = 99 end RUBY test_await_in_rescue: [<<~RUBY, 10], #{stdheader} $taval = 5 begin sleep(0.001).__await__ nomethoderror rescue sleep(0.001).__await__ $taval = 10 end RUBY test_await_in_ensure: [<<~RUBY, 11], #{stdheader} $taval = 5 begin sleep(0.001).__await__ nomethoderror rescue sleep(0.001).__await__ ensure sleep(0.001).__await__ $taval = 11 end RUBY test_await_in_ensure_expr: [<<~RUBY, -11], #{stdheader} $taval = 5 x = begin sleep(0.001).__await__ nomethoderror rescue sleep(0.001).__await__ ensure sleep(0.001).__await__ $taval = -11 end RUBY test_await_in_module: [<<~RUBY, 12], #{stdheader} $taval = 5 module XYTaim sleep(0.001).__await__ $taval = 12 end RUBY test_await_in_class: [<<~RUBY, 13], #{stdheader} $taval = 5 class XYTaic sleep(0.001).__await__ $taval = 13 end RUBY test_await_in_and: [<<~RUBY, 14], #{stdheader} ($taval = 5) && (PromiseV2.value(4).__await__) && ($taval = 14) RUBY test_await_in_plus: [<<~RUBY, 15], #{stdheader} $taval = 5 $taval = PromiseV2.value(5).__await__ + 10 RUBY # Bug before Opal 1.6: compiled autoawait expressions had wrong parentheses rules test_autoawait_awaiting: [<<~RUBY, "very correct"], #{autoawaitheader} $taval = "incorrect" $taval = PromiseV2.value("also incorrect").await.sub("also in", "") $taval = PromiseV2.value("very ").await + $taval RUBY test_autoawait_instance_exec_await: [<<~RUBY, 2*3*5*7*11*13], #{autoawaitheader} # await: *await* # backtick_javascript: true $taval = 1 module AutoawaitTemporary1 $block_with_module_self = proc do # Ensure that block.$$s is generated: self # AutoawaitTemporary2.$$eval should be true, block.$$s should be unset `\#{AutoawaitTemporary2}.$$eval` && ($taval *= PromiseV2.value(2).await) `block.$$s === null` && ($taval *= PromiseV2.value(3).await) end block = $block_with_module_self end block = $block_with_module_self module AutoawaitTemporary2; end # AutoawaitTemporary2.$$eval should be false, block.$$s should refer to AutoawaitTemporary1 `\#{AutoawaitTemporary2}.$$eval` || ($taval *= PromiseV2.value(5).await) `block.$$s === \#{AutoawaitTemporary1}` && ($taval *= PromiseV2.value(7).await) module AutoawaitTemporary2 instance_exec_await(&$block_with_module_self) end # both should get their values back after instance_exec_await is finished `\#{AutoawaitTemporary2}.$$eval` || ($taval *= PromiseV2.value(11).await) `block.$$s === \#{AutoawaitTemporary1}` && ($taval *= PromiseV2.value(13).await) RUBY } tests.each do |name,(code,expect)| define_method name do eval(code).__await__ assert_equal(expect, $taval) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_env.rb
test/nodejs/test_env.rb
require 'test/unit' require 'nodejs/env' class TestNodejsEnv < Test::Unit::TestCase def shared_test_env_has_key(method) assert_equal(false, ENV.send(method, 'should_never_be_set')) ENV['foo'] = 'bar' assert_equal(true, ENV.send(method, 'foo')) assert_equal(false, ENV.send(method, 'bar')) ENV.delete 'foo' assert_equal(false, ENV.send(method, 'foo')) end def test_include? shared_test_env_has_key('include?') end def test_has_key? shared_test_env_has_key('has_key?') end def test_member? shared_test_env_has_key('member?') end def test_key? shared_test_env_has_key('key?') end def test_get assert_equal(nil, ENV['should_never_be_set']) ENV['foo'] = 'bar' assert_equal('bar', ENV['foo']) assert_equal(nil, ENV['bar']) ENV.delete 'foo' assert_equal(nil, ENV['foo']) end def test_delete ENV['foo'] = 'bar' assert_equal('bar', ENV.delete('foo')) assert_equal(nil, ENV.delete('foo')) end def test_empty ENV['foo'] = 'bar' assert_equal(false, ENV.empty?) ENV.delete 'foo' end def test_keys ENV['foo'] = 'bar' assert_includes(ENV.keys, 'foo') ENV.delete 'foo' end def test_to_s assert_equal('ENV', ENV.to_s) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_pathname.rb
test/nodejs/test_pathname.rb
require 'test/unit' require 'nodejs' class TestNodejsPathname < Test::Unit::TestCase def self.windows_platform? `process.platform`.start_with?('win') end def test_windows_pathname_absolute assert_equal(true, Pathname.new('c:/foo').absolute?) assert_equal(true, Pathname.new('/foo').absolute?) assert_equal(true, Pathname.new('\\foo').absolute?) assert_equal(false, Pathname.new('.').absolute?) assert_equal(false, Pathname.new('foo').absolute?) end if windows_platform? end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_error.rb
test/nodejs/test_error.rb
# backtick_javascript: true require 'test/unit' require 'nodejs' class TestNodejsError < Test::Unit::TestCase def test_should_preserve_stack raise ArgumentError.new('oops') rescue => ex backtrace_line = " from nodejs/test_error.rb:#{__LINE__ - 2}" wrapped_ex = ex.exception %(context - #{ex.message}) assert(`wrapped_ex.stack`.include?(backtrace_line)) end def test_should_set_stack raise ArgumentError.new('oops') rescue => ex backtrace_line = " from nodejs/test_error.rb:#{__LINE__ - 2}" wrapped_ex = ex.exception %(context - #{ex.message}) wrapped_ex.set_backtrace ex.backtrace assert(`wrapped_ex.stack`.include?(backtrace_line)) end def test_should_get_stack raise ArgumentError.new('oops') rescue => ex backtrace_line = " from nodejs/test_error.rb:#{__LINE__ - 2}" assert(`ex.stack`.include?(backtrace_line)) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_file.rb
test/nodejs/test_file.rb
# backtick_javascript: true # Copied from cruby and modified to skip unsupported syntaxes require 'test/unit' require 'nodejs' require 'nodejs/file' class TestNodejsFile < Test::Unit::TestCase def tmpdir `require('os').tmpdir()` end def self.windows_platform? `process.platform`.start_with?('win') end def test_instantiate_without_open_mode # By default the open mode is 'r' (read only) File.write('tmp/quz', "world") file = File.new('tmp/quz') assert_equal('tmp/quz', file.path) end def test_mtime File.write('tmp/qix', "hello") file = 'tmp/qix' File.new(file, 'r') t1 = File.mtime(file) t2 = File.open(file) {|f| f.mtime} assert_kind_of(Time, t1) assert_kind_of(Time, t2) assert_equal(t1, t2) assert_raise(Errno::ENOENT) { File.mtime('nofile') } end def test_write_read path = tmpdir + "/testing_nodejs_file_implementation_#{Time.now.to_i}" contents = 'foobar' assert !File.exist?(path) File.write path, contents assert_equal(contents, File.read(path)) end def test_read_file File.write('tmp/foo', 'bar') assert_equal('bar', File.read('tmp/foo')) end def test_read_binary_image assert_match(/^\u0089PNG\r\n\u001A\n\u0000\u0000\u0000\rIHDR.*/, File.open('./test/nodejs/fixtures/cat.png', 'rb') {|f| f.read }) end def test_read_binary_utf8_file binary_text = ::File.open('./test/nodejs/fixtures/utf8.txt', 'rb') {|f| f.read} assert_equal(binary_text.encoding, Encoding::UTF_8) assert_match(/^\u00E7\u00E9\u00E0/, binary_text) utf8_text = binary_text.force_encoding('utf-8') assert_equal("çéà", utf8_text) end def test_read_binary_iso88591_file binary_text = ::File.open('./test/nodejs/fixtures/iso88591.txt', 'rb') {|f| f.read} assert_equal(binary_text.encoding, Encoding::UTF_8) assert_match(/^\u00E7\u00E9\u00E0/, binary_text) utf8_text = binary_text.force_encoding('utf-8') assert_equal("çéà", utf8_text) end def test_read_binary_win1258_file binary_text = ::File.open('./test/nodejs/fixtures/win1258.txt', 'rb') {|f| f.read} assert_equal(binary_text.encoding, Encoding::UTF_8) assert_match(/^\u00E7\u00E9\u00E0/, binary_text) utf8_text = binary_text.force_encoding('utf-8') assert_equal("çéà", utf8_text) end def test_read_each_line File.write('tmp/bar', "one\ntwo") file = File.new('tmp/bar', 'r') lines = [] file.each_line do |line| lines << line end assert_equal(2, lines.length) assert_equal("one\n", lines[0]) assert_equal('two', lines[1]) end def test_readlines File.write('tmp/quz', "one\ntwo") file = File.new('tmp/quz', 'r') lines = file.readlines assert_equal(2, lines.length) assert_equal("one\n", lines[0]) assert_equal('two', lines[1]) end def test_readlines_separator File.write('tmp/qux', "one-two") file = File.new('tmp/qux', 'r') lines = file.readlines '-' assert_equal(2, lines.length) assert_equal('one-', lines[0]) assert_equal('two', lines[1]) end def test_read_noexistent_should_raise_io_error assert_raise Errno::ENOENT do File.read('tmp/nonexistent') end end def test_mtime_noexistent_should_raise_io_error assert_raise(Errno::ENOENT) { File.mtime('tmp/nonexistent') } end def test_current_directory_should_be_a_directory assert(File.directory?('.')) end def test_current_directory_should_be_a_directory_using_pathname current_dir = Pathname.new('.') assert(current_dir.directory?) end def test_directory_check refute(File.directory?('test/nodejs/fixtures/non-existent'), 'test/nodejs/fixtures/non-existent should not be a directory') assert(File.directory?('test/nodejs/fixtures/'), 'test/nodejs/fixtures/ should be a directory') assert(File.directory?('test/nodejs/fixtures'), 'test/nodejs/fixtures should be a directory') refute(File.directory?('test/nodejs/fixtures/hello.rb'), 'test/nodejs/fixtures/hello.rb should not be a directory') end # Let's not ship our repo with symlinks, but create them on the go def with_symlinks(&block) dir_symlink = 'test/nodejs/fixtures/symlink-to-directory' file_symlink = 'test/nodejs/fixtures/symlink-to-file' File.symlink('.', dir_symlink) File.symlink('hello.rb', file_symlink) block.call(dir_symlink, file_symlink) ensure File.unlink(dir_symlink) File.unlink(file_symlink) end def test_directory_check_with_symlinks with_symlinks do |dir_symlink, file_symlink| assert(File.directory?(dir_symlink), dir_symlink+' should be a directory') assert(File.directory?(dir_symlink+'/'), dir_symlink+'/ should be a directory') refute(File.directory?(file_symlink), file_symlink+' should not be a directory') end end unless windows_platform? def test_file_check refute(File.file?('test/nodejs/fixtures/non-existent'), 'test/nodejs/fixtures/non-existent should not be a file') refute(File.file?('test/nodejs/fixtures/'), 'test/nodejs/fixtures/ should not be a file') refute(File.file?('test/nodejs/fixtures'), 'test/nodejs/fixtures should not be a file') assert(File.file?('test/nodejs/fixtures/hello.rb'), 'test/nodejs/fixtures/hello.rb should be a file') end def test_file_check_with_symlinks with_symlinks do |dir_symlink, file_symlink| refute(File.file?(dir_symlink), dir_symlink+' should not be a file') refute(File.file?(dir_symlink+'/'), dir_symlink+'/ should not be a file') assert(File.file?(file_symlink), file_symlink+' should be a file') end end unless windows_platform? def test_file_symlink? with_symlinks do |dir_symlink, file_symlink| assert(File.symlink?(file_symlink)) assert(File.symlink?(dir_symlink)) refute(File.symlink?('test/nodejs/fixtures')) refute(File.symlink?('test/nodejs/fixtures/hello.rb')) end end unless windows_platform? def test_file_readable assert !File.readable?('tmp/nonexistent') File.write('tmp/fuz', "hello") assert File.readable?('tmp/fuz') end def test_linux_separators assert_equal('/', File::SEPARATOR) assert_equal('/', File::Separator) assert_equal(nil, File::ALT_SEPARATOR) end unless windows_platform? def test_windows_separators assert_equal('/', File::SEPARATOR) assert_equal('/', File::Separator) assert_equal('\\', File::ALT_SEPARATOR) end if windows_platform? def test_windows_file_expand_path # do not use d: because its a symlink in github actions fs, leading to unexpected results drive_letter = Dir.pwd.slice(0, 2) assert_equal(Dir.pwd + '/foo/bar.js', File.expand_path('./foo/bar.js')) assert_equal(drive_letter + '/foo/bar.js', File.expand_path('/foo/bar.js')) assert_equal('c:/foo/bar.js', File.expand_path('c:/foo/bar.js')) assert_equal('c:/foo/bar.js', File.expand_path('c:\\foo\\bar.js')) assert_equal('c:/foo/bar.js', File.expand_path('bar.js', 'c:\\foo')) assert_equal('c:/baz/bar.js', File.expand_path('\\baz\\bar.js', 'c:\\foo')) assert_equal('c:/bar.js', File.expand_path('\\..\\bar.js', 'c:\\foo\\baz')) assert_equal('c:/bar.js', File.expand_path('\\..\\bar.js', 'c:\\foo\\baz\\')) assert_equal('c:/foo/baz/bar.js', File.expand_path('baz\\bar.js', 'c:\\foo')) assert_equal('c:/baz/bar.js', File.expand_path('baz\\bar.js', 'c:\\foo\\..')) assert_equal('f:/', File.expand_path('f:'), 'should add a trailing slash when the path is d:') assert_equal('g:/', File.expand_path('g:/'), 'should preserve the trailing slash when the path d:/') assert_equal(Dir.pwd, File.expand_path(drive_letter), 'should expand to the current directory when the path is c: (and the current directory is located in the c drive)') assert_equal(drive_letter + '/', drive_letter + '/', 'should return c:/ when the path is c:/ because the path is absolute') end if windows_platform? def test_linux_file_expand_path assert_equal(Dir.pwd + '/foo/bar.js', File.expand_path('./foo/bar.js')) assert_equal(Dir.home + '/foo/bar.js', File.expand_path('~/foo/bar.js')) assert_equal(Dir.home + '/foo/bar.js', File.expand_path('~/foo/bar.js', '/base/dir')) assert_equal('/base/dir/foo/bar.js', File.expand_path('./foo/bar.js', '/base/dir')) assert_equal(Dir.home + '/workspace/foo/bar.js', File.expand_path('./foo/bar.js', '~/workspace')) end unless windows_platform? def test_join assert_equal('usr/bin', File.join('usr', 'bin')) assert_equal('//a/b', File.join('//a', 'b')) end def test_join_supports_any_number_of_arguments assert_equal("a/b/c/d", File.join("a", "b", "c", "d")) end def test_join_handles_leading_parts_edge_cases assert_equal("/bin", File.join("/bin")) assert_equal("/bin", File.join("/", "bin")) assert_equal("/bin", File.join("/", "/bin")) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_tracepoint_end.rb
test/nodejs/test_tracepoint_end.rb
# frozen_string_literal: true # await: *await require "test/unit" require "corelib/trace_point" class TestTracePointEnd < Test::Unit::TestCase HEADER = <<~RUBY # await: true require "await" RUBY def eval_and_await(code) eval(code).__await__ end def test_end_after_class_body_sync code = <<~RUBY #{HEADER} $trace = [] tp = TracePoint.new(:end) { |tp| $trace << :end } tp.enable class TPESync $trace << :in_body_before $trace << :in_body_after end $trace << :after_class tp.disable $trace RUBY trace = eval_and_await(code) assert_equal [:in_body_before, :in_body_after, :end, :after_class], trace end def test_end_after_class_body_async code = <<~RUBY #{HEADER} $trace = [] tp = TracePoint.new(:end) { |tp| $trace << :end } tp.enable class TPEAsync $trace << :in_body_before sleep(0.001).__await__ $trace << :in_body_after end $trace << :after_class tp.disable $trace RUBY trace = eval_and_await(code) assert_equal [:in_body_before, :in_body_after, :end, :after_class], trace end def test_end_after_module_body_sync code = <<~RUBY #{HEADER} $trace = [] tp = TracePoint.new(:end) { |tp| $trace << :end } tp.enable module TPESyncMod $trace << :in_body_before $trace << :in_body_after end $trace << :after_module tp.disable $trace RUBY trace = eval_and_await(code) assert_equal [:in_body_before, :in_body_after, :end, :after_module], trace end def test_end_after_module_body_async code = <<~RUBY #{HEADER} $trace = [] tp = TracePoint.new(:end) { |tp| $trace << :end } tp.enable module TPEAsyncMod $trace << :in_body_before sleep(0.001).__await__ $trace << :in_body_after end $trace << :after_module tp.disable $trace RUBY trace = eval_and_await(code) assert_equal [:in_body_before, :in_body_after, :end, :after_module], trace end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_opal_builder.rb
test/nodejs/test_opal_builder.rb
require 'test/unit' require 'nodejs' require 'opal-builder' class TestNodejsOpalBuilder < Test::Unit::TestCase def test_should_build_simple_ruby_file builder = Opal::Builder.new builder.append_paths('.') result = builder.build('test/nodejs/fixtures/hello.rb') assert(/self\.\$puts\("Hello world"\)/.match(result.to_s)) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_yaml.rb
test/nodejs/test_yaml.rb
require 'test/unit' require 'nodejs' require 'nodejs/yaml' class TestYAML < Test::Unit::TestCase YAMLDOC = <<~YAML --- string: hello world array: [1,2,3] YAML YAMLSTRUCT = { "string" => "hello world", "array" => [1,2,3] } def test_should_parse_yaml assert_equal(YAML.load(YAMLDOC), YAMLSTRUCT) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_file_encoding.rb
test/nodejs/test_file_encoding.rb
require 'test/unit' require 'nodejs' require 'nodejs/file' class TestNodejsFileEncoding < Test::Unit::TestCase def test_force_encoding_raw_text_to_utf8 raw_text = 'çéà' assert_equal(raw_text.encoding, Encoding::UTF_8) utf8_text = raw_text.force_encoding('utf-8') assert_equal("çéà", utf8_text) end def test_force_encoding_from_binary_to_utf8 raw_text = "\xC3\xA7\xC3\xA9\xC3\xA0" assert_equal(raw_text.encoding, Encoding::UTF_8) utf8_text = raw_text.force_encoding('utf-8') assert_equal("çéà", utf8_text) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_string.rb
test/nodejs/test_string.rb
# backtick_javascript: true require 'test/unit' require 'nodejs' class TestString < Test::Unit::TestCase def test_should_get_bytes assert_equal('foo'.bytesize, 3) assert_equal('foo'.each_byte.to_a, [102, 111, 111]) assert_equal('foo'.bytes, [102, 111, 111]) assert_equal('foo'.bytes, [102, 111, 111]) end def test_frozen # Commented out examples somehow work in the strict mode, # but otherwise they don't. I have unfortunately no idea # on where it's mangled, but then I don't see it really # as a really harmful thing. #assert_equal((-'x').frozen?, true) assert_equal((+'x').frozen?, false) #assert_equal((-+-'x').frozen?, true) assert_equal((+-+'x').frozen?, false) #assert_equal((`'x'`).frozen?, true) assert_equal((+`'x'`).frozen?, false) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/test_dir.rb
test/nodejs/test_dir.rb
# backtick_javascript: true # Copied from cruby and modified to skip unsupported syntaxes require 'test/unit' require 'nodejs' require 'nodejs/dir' class TestNodejsDir < Test::Unit::TestCase def glob_base_test_dir tmpdir + "/testing_nodejs_dir_glob_implementation_#{Time.now.to_i}" end def tmpdir `require('os').tmpdir()` end def normalize_glob(path) path.gsub "\\", "/" end def test_dir_entries path = tmpdir + "/testing_nodejs_dir_entries_implementation_#{Time.now.to_i}" Dir.mkdir(path) result = Dir.entries(path) assert_equal(0, result.length) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.entries(path) assert_equal(2, result.length) end def test_dir_glob_single_directory path = glob_base_test_dir + "/single_directory" Dir.mkdir(path) result = Dir.glob(normalize_glob(path)) assert_equal(1, result.length) end def test_dir_glob_any_files_in_directory path = glob_base_test_dir + "/any_files_in_directory" Dir.mkdir(path) result = Dir.glob(normalize_glob(path + '/*')) assert_equal(result.length, 0) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.glob(normalize_glob(path + '/*')) assert_equal(result.length, 2) end def test_dir_glob_start_with_files_in_directory path = glob_base_test_dir + "/start_with_files_in_directory" Dir.mkdir(path) result = Dir.glob(normalize_glob(path + '/*')) assert_equal(result.length, 0) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.glob(normalize_glob(path + '/ba*')) assert_equal(2, result.length) end def test_dir_glob_end_with_files_in_directory path = glob_base_test_dir + "/end_with_files_in_directory" Dir.mkdir(path) result = Dir.glob(normalize_glob(path + '/*')) assert_equal(result.length, 0) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.glob(normalize_glob(path + '/*z')) assert_equal(1, result.length) end def test_dir_glob_specific_files path = glob_base_test_dir + "/specific_files" Dir.mkdir(path) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.glob([normalize_glob(path + '/baz'), normalize_glob(path + '/bar')]) assert_equal(2, result.length) result = Dir.glob(normalize_glob(path)) assert_equal(1, result.length) end def test_dir_glob_include_subdir base_path = glob_base_test_dir + "/include_subdir" path = base_path + "/subdir" Dir.mkdir(path) Dir.mkdir(path) File.open(path + '/bar', "w") {} File.open(path + '/baz', "w") {} result = Dir.glob(normalize_glob(base_path + '/*/*')) assert_equal(2, result.length) end def test_dir_glob_recursive base_path = glob_base_test_dir + "/recursive" Dir.mkdir(base_path) File.open(base_path + '/1', "w") {} File.open(base_path + '/2', "w") {} path = base_path + "/subdir" Dir.mkdir(path) File.open(path + '/3', "w") {} File.open(path + '/4', "w") {} result = Dir.glob(normalize_glob(base_path + '/**/*')) assert_equal(5, result.length) end def test_dir_glob_any_directories base_path = glob_base_test_dir + "/recursive" Dir.mkdir(base_path) File.open(base_path + '/1', "w") {} File.open(base_path + '/2', "w") {} path = base_path + "/subdir" Dir.mkdir(path) File.open(path + '/3', "w") {} File.open(path + '/4', "w") {} result = Dir.glob(normalize_glob(base_path + '/**')) assert_equal(3, result.length) end def test_dir_glob_single_depth base_path = glob_base_test_dir + "/single_depth" Dir.mkdir(base_path) File.open(base_path + '/1', "w") {} File.open(base_path + '/2', "w") {} path = base_path + "/subdir" Dir.mkdir(path) File.open(path + '/3', "w") {} File.open(path + '/4', "w") {} result = Dir.glob(normalize_glob(base_path + '/*/*')) assert_equal(2, result.length) end def test_dir_glob_multiple_depth base_path = glob_base_test_dir + "/multiple_depth" path = base_path + "/1/2/3" Dir.mkdir(path) File.open(path + '/foo', "w") {} File.open(path + '/bar', "w") {} result = Dir.glob(normalize_glob(base_path + '/**/foo')) assert_equal(1, result.length) result = Dir.glob(normalize_glob(base_path + '/**/*')) assert_equal(5, result.length) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/test/nodejs/fixtures/hello.rb
test/nodejs/fixtures/hello.rb
puts "Hello world"
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/spec_helper.rb
spec/spec_helper.rb
# backtick_javascript: true require 'opal' require 'set' require 'opal/platform' require 'opal-parser' require 'mspec' require 'mspec/version' require 'support/mspec_rspec_adapter' require 'support/guard_platform' require 'mspec-opal/runner' # Node v0.12 as well as Google Chrome/V8 42.0.2311.135 (64-bit) # showed to need more tolerance (ruby spec default is 0.00003) TOLERANCE = 0.00004 ENV['MSPEC_RUNNER'] = true # Trigger autoloading, needed by `Module.constants` # in `spec/ruby/core/module/constants_spec.rb`. Dir module Kernel def opal_parse(str, file='(string)') Opal::Parser.new.parse str, file end def eval_js(javascript) `eval(javascript)` end end # To make MSpec happy require 'thread' require 'corelib/math' require 'mspec/utils/script' # Needed by DottedFormatter require 'mspec-opal/formatters'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string_spec.rb
spec/opal/core/string_spec.rb
# backtick_javascript: true require 'spec_helper' describe 'Encoding' do it 'supports US-ASCII' do skip if OPAL_PLATFORM == 'deno' # see filters/platform/deno "è".encoding.name.should == 'UTF-8' "è".force_encoding('ASCII').should == "\xC3\xA8" "è".force_encoding('ascii').should == "\xC3\xA8" "è".force_encoding('US-ASCII').should == "\xC3\xA8" "è".force_encoding('us-ascii').should == "\xC3\xA8" "è".force_encoding('ASCII-8BIT').should == "\xC3\xA8" "è".force_encoding('ascii-8bit').should == "\xC3\xA8" "è".force_encoding('BINARY').should == "\xC3\xA8" "è".force_encoding('binary').should == "\xC3\xA8" end describe '.find' do it 'finds the encoding regardless of the case' do Encoding.find('ASCII').should == Encoding::ASCII Encoding.find('ascii').should == Encoding::ASCII Encoding.find('US-ASCII').should == Encoding::ASCII Encoding.find('us-ascii').should == Encoding::ASCII Encoding.find('ASCII-8BIT').should == Encoding::BINARY Encoding.find('ascii-8bit').should == Encoding::BINARY Encoding.find('BINARY').should == Encoding::BINARY Encoding.find('binary').should == Encoding::BINARY end end end describe 'strip methods' do def strip_cases(before, after, method) before = before ? 1 : 0 after = after ? 1 : 0 it 'strip spaces' do "#{" " * before}ABC#{" " * after}".send(method).should == "ABC" end it 'strips NUL bytes' do "#{"\0" * before}ABC#{"\0" * after}".send(method).should == "ABC" end it "doesn't strip NBSPs" do "#{"\u{a0}" * before}ABC#{"\u{a0}" * after}".send(method).should != "ABC" end it "strips all other supported whitespace characters" do "#{"\r\n\t\v\f" * before}ABC#{"\r\n\t\v\f" * after}".send(method).should == "ABC" end end describe '#lstrip' do strip_cases true, false, :lstrip end describe '#rstrip' do strip_cases false, true, :rstrip end describe '#strip' do strip_cases true, true, :strip end end describe 'Unicode Astral Plane' do # '𝌆' is a 2 part surrogate # in Ruby: '𝌆'.length == 1 # in JavaScript: '𝌆'.length == 2 # '𝌆'.charCodeAt(0) == 55348, first half of surrogate, high # '𝌆'.charCodeAt(1) == 57094, second half of surrogate, low it 'reports the correct String #length' do 'a𝌆'.size.should == 2 end it 'returns the correct character or string by #[]' do 'a𝌆'[1].should == '𝌆' 'a𝌆a𝌆a𝌆'[1..3].should == '𝌆a𝌆' 'a𝌆a𝌆a𝌆'[-5..-3].should == '𝌆a𝌆' 'a𝌆a𝌆a𝌆'['𝌆'].should == '𝌆' 'a𝌆a𝌆a𝌆'['𝌆a'].should == '𝌆a' 'a𝌆a𝌆a𝌆'[/a/].should == 'a' 'a𝌆a𝌆a𝌆'[/𝌆/].should == '𝌆' 'a𝌆a𝌆a𝌆'[/#{`String.fromCharCode(55348)`}/].should == nil 'a𝌆a𝌆a𝌆'[/#{`String.fromCharCode(57094)`}/].should == nil 'a𝌆a𝌆a𝌆'[Regexp.new(`String.fromCharCode(55348)`)].should == nil 'a𝌆a𝌆a𝌆'[Regexp.new(`String.fromCharCode(57094)`)].should == nil end it 'correctly compares by #<=>' do str1 = "ça va bien" str2 = "c\u0327a va bien" (str1 <=> str2).should == 1 (str1.unicode_normalize <=> str2.unicode_normalize).should == 0 end it 'correctly compares by #==' do str1 = "ça va bien" str2 = "c\u0327a va bien" (str1 == str2).should == false (str1.unicode_normalize == str2.unicode_normalize).should == true end it 'does #center correctly' do 'a𝌆a'.center(4).should == 'a𝌆a ' end it 'does #ljust correctly' do 'a𝌆a'.ljust(4).should == 'a𝌆a ' end it 'does #rjust correctly' do 'a𝌆a'.rjust(4).should == ' a𝌆a' end it 'returns #chr correctly' do '𝌆a'.chr.should == '𝌆' end it '#delete_prefix correctly' do '𝌆a'.delete_prefix(`String.fromCharCode(55348)`).should == '𝌆a' '𝌆a'.delete_prefix('𝌆').should == 'a' end it '#delete_suffix correctly' do 'a𝌆'.delete_suffix(`String.fromCharCode(57094)`).should == 'a𝌆' 'a𝌆'.delete_suffix('𝌆').should == 'a' end it 'correctly reports #end_with?' do 'a𝌆'.end_with?(`String.fromCharCode(57094)`).should == false 'a𝌆'.end_with?('𝌆').should == true end it 'correctly reports #include?' do 'a𝌆'.include?(`String.fromCharCode(55348)`).should == false 'a𝌆'.include?('𝌆').should == true 'a𝌆a𝌆'.include?('𝌆a').should == true end it 'returns correct #index' do 'a𝌆a'.index(`String.fromCharCode(55348)`).should == nil 'a𝌆a'.index('𝌆').should == 1 'a𝌆a𝌆a'.index('𝌆a').should == 1 end it 'returns correct #partition' do '𝌆a𝌆a𝌆a'.partition(`String.fromCharCode(55348)`).should == ['𝌆a𝌆a𝌆a', '', ''] '𝌆a𝌆a𝌆a'.partition('𝌆').should == ['', '𝌆', 'a𝌆a𝌆a'] end it '#reverse correctly' do '𝌆a𝌆a𝌆a'.reverse.should == 'a𝌆a𝌆a𝌆' end it 'returns correct #rindex' do 'a𝌆a'.rindex(`String.fromCharCode(55348)`).should == nil 'a𝌆a'.rindex('𝌆').should == 1 'a𝌆a𝌆a'.rindex('𝌆a').should == 3 end it 'returns correct #rpartition' do '𝌆a𝌆a𝌆a'.rpartition(`String.fromCharCode(55348)`).should == ['', '', '𝌆a𝌆a𝌆a'] '𝌆a𝌆a𝌆a'.rpartition('𝌆').should == ['𝌆a𝌆a', '𝌆', 'a'] end it 'correctly reports #start_with?' do '𝌆a'.start_with?(`String.fromCharCode(55348)`).should == false '𝌆a'.start_with?('𝌆').should == true end it 'transliterates correctly with #tr' do '𝌆a𝌆a𝌆a'.tr(`String.fromCharCode(55348)`, 'c').should == '𝌆a𝌆a𝌆a' '𝌆a𝌆a𝌆a'.tr('𝌆', 'c').should == 'cacaca' '𝌆a𝌆a𝌆a'.tr('a', 'c').should == '𝌆c𝌆c𝌆c' '𝌆a𝌆a𝌆a'.tr('𝌆a', 'bc').should == 'bcbcbc' '𝌆a𝌆b𝌆a'.tr('𝌆b', 'bc').should == 'babcba' end it 'transliterates correctly with #tr_s' do '𝌆a𝌆a𝌆a'.tr_s(`String.fromCharCode(55348)`, 'c').should == '𝌆a𝌆a𝌆a' '𝌆a𝌆a𝌆a'.tr_s('𝌆', 'c').should == 'cacaca' '𝌆a𝌆a𝌆a'.tr_s('a', 'c').should == '𝌆c𝌆c𝌆c' '𝌆a𝌆a𝌆a'.tr_s('𝌆a', 'bc').should == 'bcbcbc' '𝌆a𝌆b𝌆a'.tr_s('𝌆b', 'bc').should == 'babcba' '𝌆𝌆𝌆aaa'.tr_s('𝌆a', 'bc').should == 'bc' end it 'splits correctly' do '𝌆a𝌆a𝌆a'.split('').should == ["𝌆", "a", "𝌆", "a", "𝌆", "a"] '𝌆a𝌆a𝌆a'.split(`String.fromCharCode(55348)`).should == ['𝌆a𝌆a𝌆a'] '𝌆a𝌆a𝌆a'.split(`String.fromCharCode(57094)`).should == ['𝌆a𝌆a𝌆a'] '𝌆a𝌆a𝌆a'.split('a').should == ["𝌆", "𝌆", "𝌆"] '𝌆a𝌆a𝌆a'.split('𝌆').should == ["", "a", "a", "a"] end it 'chomps correctly' do '𝌆a𝌆a𝌆'.chomp(`String.fromCharCode(57094)`).should == '𝌆a𝌆a𝌆' '𝌆a𝌆a𝌆'.chomp(`String.fromCharCode(55348) + "a𝌆"`).should == '𝌆a𝌆a𝌆' '𝌆a𝌆a𝌆'.chomp("𝌆").should == '𝌆a𝌆a' '𝌆a𝌆a𝌆'.chomp("a𝌆").should == '𝌆a𝌆' end it 'chops correctly' do '𝌆a𝌆a𝌆'.chop.should == '𝌆a𝌆a' end it 'skips the surrogate range in #next and #succ' do s = `String.fromCharCode(0xD7FF)` s.next.ord.should == 0xE000 s.succ.ord.should == 0xE000 end it 'skips the surrogate range in #upto' do res = [] s = `String.fromCharCode(0xD7FF)` s.upto(`String.fromCharCode(0xE000)`) do |v| res << v.ord end res.should == [0xD7FF, 0xE000] end it 'counts correctly' do '𝌆a𝌆a𝌆a'.count(`String.fromCharCode(55348)`).should == 0 '𝌆a𝌆a𝌆a'.count(`String.fromCharCode(57094)`).should == 0 '𝌆a𝌆a𝌆a'.count(`String.fromCharCode(57094) + 'a'`).should == 3 '𝌆a𝌆a𝌆a'.count(`String.fromCharCode(55348) + 'a'`).should == 3 '𝌆a𝌆a𝌆a'.count(`String.fromCharCode(55348) + '𝌆'`).should == 3 '𝌆a𝌆a𝌆a'.count('𝌆').should == 3 '𝌆a𝌆a𝌆a'.count('a𝌆').should == 6 end it 'deletes correctly' do '𝌆a𝌆a𝌆a'.delete(`String.fromCharCode(55348)`).should == '𝌆a𝌆a𝌆a' '𝌆a𝌆a𝌆a'.delete(`String.fromCharCode(57094)`).should == '𝌆a𝌆a𝌆a' '𝌆a𝌆a𝌆a'.delete(`String.fromCharCode(57094) + 'a'`).should == '𝌆𝌆𝌆' '𝌆a𝌆a𝌆a'.delete(`String.fromCharCode(55348) + 'a'`).should == '𝌆𝌆𝌆' '𝌆a𝌆a𝌆a'.delete(`String.fromCharCode(55348) + '𝌆'`).should == 'aaa' '𝌆a𝌆a𝌆a'.delete('𝌆').should == 'aaa' '𝌆a𝌆a𝌆a'.delete('a𝌆').should == '' end it 'iterates through lines correctly' do '𝌆a𝌆a𝌆a'.each_line(`String.fromCharCode(55348)`).count.should == 1 '𝌆a𝌆a𝌆a'.each_line(`String.fromCharCode(57094)`).count.should == 1 '𝌆a𝌆a𝌆a'.each_line('𝌆').count.should == 4 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/exception_spec.rb
spec/opal/core/exception_spec.rb
# backtick_javascript: true require 'spec_helper' describe "Native exception" do it "handles messages for native exceptions" do exception = `new Error("native message")` exception.message.should == "native message" end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/module_spec.rb
spec/opal/core/module_spec.rb
module ModuleSubclassIncludedSpec class Module1 < ::Module def included(_descendant) $ScratchPad << 'A included' end end class Module2 < Module1 def included(_descendant) $ScratchPad << 'B included' end end M0 = Module.new M1 = Module1.new M2 = Module2.new end module ModuleCVarSpec module Mod0 def cvar0; @@cvar; end def cvarx0; @@cvarx ||= 5; end def cvary0; @@cvary; 0; end def cvarz0; @@cvarz = @@cvarz || 5; end end module Mod1 include Mod0 @@cvar = 10 def cvar1; @@cvar; end def cvar1=(new); @@cvar=new; end end module Mod2 include Mod1 def cvar2; @@cvar; end def cvar2=(new); @@cvar=new; end end end describe 'Module' do it '#included gets called in subclasses (regression for https://github.com/opal/opal/issues/1900)' do $ScratchPad = [] klass = Class.new klass.include ::ModuleSubclassIncludedSpec::M0 klass.include ::ModuleSubclassIncludedSpec::M1 klass.include ::ModuleSubclassIncludedSpec::M2 $ScratchPad.should == ['A included', 'B included'] end it "can access ancestor's @@cvar" do klass = Class.new klass.include ::ModuleCVarSpec::Mod2 klass.new.cvar1.should == 10 klass.new.cvar2.should == 10 klass.new.cvar2 = 50 klass.new.cvar1.should == 50 klass.new.cvar2.should == 50 klass.new.cvarx0.should == 5 klass.new.cvary0.should == 0 ->{ klass.new.cvarz0 }.should raise_error NameError ->{ klass.new.cvar0 }.should raise_error NameError end it "can be set to a constant while being frozen" do OPAL_SPEC_MODULE = Module.new.freeze OPAL_SPEC_CLASS = Class.new.freeze OPAL_SPEC_MODULE.class.should == Module OPAL_SPEC_CLASS.class.should == Class end describe "updates iclass" do def included_structures mod = Module.new { def method_to_remove; end } klass = Class.new { include mod } [mod, klass] end def prepended_structures mod = Module.new { def method_to_remove; end } klass = Class.new { prepend mod } [mod, klass] end it "whenever a new method is added to an included module" do mod, klass = included_structures ->{ klass.new.nonexistent }.should raise_error NoMethodError mod.class_exec { def added_method; end } ->{ klass.new.added_method }.should_not raise_error NoMethodError end it "whenever a new method is added to a prepended module" do mod, klass = prepended_structures ->{ klass.new.nonexistent }.should raise_error NoMethodError mod.class_exec { def added_method; end } ->{ klass.new.added_method }.should_not raise_error NoMethodError end it "whenever a method is removed from an included module" do mod, klass = included_structures ->{ klass.new.nonexistent }.should raise_error NoMethodError ->{ klass.new.method_to_remove }.should_not raise_error NoMethodError mod.class_exec { remove_method :method_to_remove } ->{ klass.new.method_to_remove }.should raise_error NoMethodError end it "whenever a method is removed from a prepended module" do mod, klass = prepended_structures ->{ klass.new.nonexistent }.should raise_error NoMethodError ->{ klass.new.method_to_remove }.should_not raise_error NoMethodError mod.class_exec { remove_method :method_to_remove } ->{ klass.new.method_to_remove }.should raise_error NoMethodError end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/iterable_props_spec.rb
spec/opal/core/iterable_props_spec.rb
# backtick_javascript: true require 'spec_helper' describe 'Iterable props defined by Opal on core JS objects' do %x{ function iterableKeysOf(obj) { var result = []; for (var key in obj) { result.push(key); } return result; } } it 'is empty for numbers' do `iterableKeysOf(1)`.should == [] end it 'is empty for strings' do `iterableKeysOf('123')`.should == ['0', '1', '2'] # indexes, in JS they are iterable by default `iterableKeysOf(new String('123'))`.should == ['0', '1', '2'] # indexes, in JS they are iterable by default end it 'is empty for plain objects' do `iterableKeysOf({})`.should == [] end it 'is empty for boolean' do `iterableKeysOf(true)`.should == [] `iterableKeysOf(false)`.should == [] end it 'is empty for regexp' do `iterableKeysOf(/regexp/)`.should == [] end it 'is empty for functions' do `iterableKeysOf(function() {})`.should == [] end it 'is empty for dates' do `iterableKeysOf(new Date())`.should == [] end it 'is empty for errors' do `iterableKeysOf(new Error('message'))`.should == [] end it 'is empty for Math' do `iterableKeysOf(Math)`.should == [] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime_spec.rb
spec/opal/core/runtime_spec.rb
# backtick_javascript: true require 'spec_helper' describe 'javascript access using .JS' do it 'should call javascript methods via .JS.method()' do "a1234b5678c".JS.indexOf('c').should == 10 "a1234b5678c".JS.replace(`/[0-9]/g`, '').should == 'abc' end it 'should call javascript methods via .JS.method arg' do ("a1234b5678c".JS.indexOf 'c').should == 10 ("a1234b5678c".JS.replace `/[0-9]/g`, '').should == 'abc' end it 'should call javascript methods with blocks via .JS.method' do f = `{a:function(f){return f(1) + f(2)}}` f.JS.a{|v| v*2}.should == 6 v = f.JS.a do |v| v*2 end v.should == 6 end it 'should call javascript methods with args and blocks via .JS.method' do f = `{a:function(a, f){return f(a, 1) + f(a, 2)}}` f.JS.a(3){|b, v| b+v*2}.should == 12 v = f.JS.a 3 do |b, v| b+v*2 end v.should == 12 end it 'should support javascript properties via .JS[]' do "a1234b5678c".JS['length'].should == 11 `{a:1}`.JS['a'].should == 1 `{a:1}`.JS['a'].should == 1 [2, 4].JS[0].should == 2 [2, 4].JS[1].should == 4 [2, 4].JS[:length].should == 2 end it 'should be chainable' do "a1234b5678c".JS.replace(`/[0-9]/g`, '').JS.toUpperCase.should == 'ABC' "a1234b5678c".JS.replace(`/[0-9]/g`, '').JS[:length].should == 3 "a1234b5678c".JS[:length].JS.toString.should == "11" `{a:{b:1}}`.JS[:a].JS[:b].JS.toString.should == '1' f = `{a:function(f){return {b: function(f2){return f(f2(1)) + f(f2(2))}}}}` f.JS.a{|v| v*2}.JS.b{|v| v*3}.should == 18 end it 'should set javascript properties via .JS[arg] = rhs' do a = `{}` a.JS[:foo] = 1 a.JS[:foo].should == 1 `a["foo"]`.should == 1 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/hash_spec.rb
spec/opal/core/hash_spec.rb
# backtick_javascript: true describe 'Hash' do it 'works with object-strings with regards to deleting' do h = {`new String('a')` => 'a'} k = h.keys.first h.delete(k) h.inspect.should == '{}' end it 'compacts nil and JavaScript null and undefined values' do h = { a: nil, b: `null`, c: `undefined`, d: 1 } expect(h.size).to eq 4 expect(h.compact.size).to eq 1 h.compact! expect(h.size).to eq 1 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/object_id_spec.rb
spec/opal/core/object_id_spec.rb
# backtick_javascript: true require 'spec_helper' describe "Opal.uid()" do it "returns even sequential numbers in increments of 2" do %x{ var id0 = Opal.uid(), id1 = Opal.uid(), id2 = Opal.uid(), id3 = Opal.uid(), id4 = Opal.uid(); } modulo = `id0` % 2 modulo.should == 0 `id1`.should == `id0` + 2 `id2`.should == `id0` + 4 `id3`.should == `id0` + 6 `id4`.should == `id0` + 8 end end describe "FalseClass#object_id" do it "returns 0" do false.object_id.should == 0 end end describe "TrueClass#object_id" do it "returns 2" do true.object_id.should == 2 end end describe "NilClass#object_id" do it "returns 4" do nil.object_id.should == 4 end end describe "Numeric#object_id" do it "returns (self * 2) + 1" do skip if OPAL_PLATFORM == "bun" 0.object_id.should == 1 1.object_id.should == 3 2.object_id.should == 5 420.object_id.should == 841 -2.object_id.should == -3 -1.object_id.should == -1 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/helpers_spec.rb
spec/opal/core/helpers_spec.rb
require 'spec_helper' describe Opal do context '.instance_variable_name!' do it 'does not use regular expressions on Opal level, so $` stays the same' do 'some string' =~ /string/ post_match = $` Opal.instance_variable_name!(:@ivar_name) expect($`).to eq(post_match) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/time_spec.rb
spec/opal/core/time_spec.rb
require 'spec_helper' require 'time' # rubyspec does not have specs for these listed methods describe Time do describe '<=>' do it 'returns -1 when self is less than other' do (Time.new(2015, 1, 1) <=> Time.new(2015, 1, 2)).should == -1 end it 'returns 0 when self is equal to other' do (Time.new(2015, 1, 1) <=> Time.new(2015, 1, 1)).should == 0 end it 'returns 1 when self is greater than other' do (Time.new(2015, 1, 2) <=> Time.new(2015, 1, 1)).should == 1 end it 'returns nil when compared to non-Time objects' do (Time.new <=> nil).should == nil end end describe "#==" do it "returns true if self is equal to other date" do (Time.new(2013, 9, 13) == Time.new(2013, 9, 13)).should == true end it "returns false if self is not equal to other date" do (Time.new(2013, 10, 2) == Time.new(2013, 10, 11)).should == false end it 'returns false when compared to non-Time objects' do (Time.new == nil).should == false (Time.new == Object.new).should == false end end describe '#zone' do context 'with different TZs on Tue Jun 20 20:50:08 UTC 2017' do it 'zone is +12' do time = Time.now # export TZ="/usr/share/zoneinfo/Pacific/Fiji"; node -e 'console.log(new Date().toString())' time.JS[:toString] = -> { 'Wed Jun 21 2017 08:42:01 GMT+1200 (+12)' } time.zone.should == '+12' # export TZ="/usr/share/zoneinfo/Europe/Rome"; node -e 'console.log(new Date().toString())' time.JS[:toString] = -> { 'Tue Jun 20 2017 22:52:57 GMT+0200 (CEST)' } time.zone.should == 'CEST' # export TZ="/usr/share/zoneinfo/Europe/Rome"; node -e 'console.log(new Date().toString())' time.JS[:toString] = -> { 'Tue Jun 20 2017 23:56:54 GMT+0300 (MSK)' } time.zone.should == 'MSK' # https://github.com/opal/opal/issues/403 time.JS[:toString] = -> { 'Wed May 07 2014 11:59:05 GMT+0300 (Финляндия (лето))' } time.zone.should == 'Финляндия (лето)' end end end describe '#utc_offset' do it 'returns 0 if the date is UTC' do Time.new.utc.utc_offset.should == 0 end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/boolean_spec.rb
spec/opal/core/boolean_spec.rb
require 'spec_helper' describe "TrueClass/FalseClass" do it 'correctly resolves a boolean class' do expect(true.class).to eq(TrueClass) expect(false.class).to eq(FalseClass) expect(true.class).not_to eq(false.class) end it 'correctly resolves a boolean class with #is_a?' do expect(true.is_a? TrueClass).to be_true expect(false.is_a? FalseClass).to be_true expect(false.is_a? TrueClass).to be_false expect(true.is_a? FalseClass).to be_false end it 'correctly resolves a boolean class with #===' do expect(TrueClass === true).to be_true expect(FalseClass === false).to be_true expect(TrueClass === false).to be_false expect(FalseClass === true).to be_false expect(TrueClass === 6).to be_false expect(true === true).to be_true expect(false === false).to be_true end it 'allows defining methods on TrueClass/FalseClass' do class TrueClass def test_opal false end end class FalseClass def test_opal true end end expect(true.test_opal).to be_false expect(false.test_opal).to be_true end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/language_spec.rb
spec/opal/core/language_spec.rb
# backtick_javascript: true require 'spec_helper' describe "generated method names" do it "does not conflict with local Ruby variables" do Class.new { value = 123 def value 456 end value.should == 123 } end it "does not conflict with local JS variables" do Class.new { `var value = 123;` def value 456 end `value`.should == 123 } end end describe "Bridging" do it "does not remove singleton methods of bridged classes" do `typeof(String.call)`.should == "function" end end describe "Constants" do it "doesn't raise error when a JS falsey constant is referenced" do z = Class.new { C1 = 0 C2 = nil C3 = false C4 = '' C5 = C3 } [z::C1, z::C2, z::C3, z::C4, z::C5].should == [0, nil, false, '', false] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/to_proc_spec.rb
spec/opal/core/string/to_proc_spec.rb
require 'spec_helper' describe "Symbol#to_proc" do # bug #2417 it "correctly passes method name to #method_missing" do obj = Object.new def obj.method_missing(*args); args; end; result = :a.to_proc.call(obj, 6, 7) result.should == [:a, 6, 7] end it "correctly passes a block to #method_missing" do obj = Object.new block = ->{} def obj.method_missing(*args, &block); block; end; result = :a.to_proc.call(obj, 1, 2, 3, &block) result.should == block end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/gsub_spec.rb
spec/opal/core/string/gsub_spec.rb
require 'spec_helper' describe 'String' do describe '#gsub' do it 'handles recursive gsub' do pass_slot_rx = /{(\d+)}/ recurse_gsub = -> text { text.gsub(pass_slot_rx) { index = $1.to_i if index == 0 recurse_gsub.call '{1}' else 'value' end } } result = recurse_gsub.call '<code>{0}</code>' result.should == '<code>value</code>' end it 'works well with zero-length matches' do expect("test".gsub(/^/, '2')).to eq "2test" expect("test".gsub(/$/, '2')).to eq "test2" expect("test".gsub(/\b/, '2')).to eq "2test2" end it "doesn't override $~ when it's inspected" do 'a:b'.gsub(/([a-z]):([a-z])/) do $~.inspect target, content = $1, $2 expect([target, content]).to eq(['a', 'b']) end end end describe '#sub' do it 'works well with zero-length matches' do expect("test".sub(/^/, '2')).to eq "2test" expect("test".sub(/$/, '2')).to eq "test2" expect("test".sub(/\b/, '2')).to eq "2test" end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/subclassing_spec.rb
spec/opal/core/string/subclassing_spec.rb
require 'spec_helper' class MyStringSubclass < String attr_reader :v def initialize(s, v) super(s) @v = v end end describe "String subclassing" do it "should call initialize for subclasses" do c = MyStringSubclass.new('s', 5) [c, c.v].should == ['s', 5] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/unpack_spec.rb
spec/opal/core/string/unpack_spec.rb
require 'spec_helper' describe 'String#unpack' do it 'correctly unpacks with U* strings with latin-1 characters' do 'café'.unpack('U*').should == [99, 97, 102, 233] [99, 97, 102, 233].pack('U*').unpack('U*').should == [99, 97, 102, 233] end it 'correctly unpacks with U* strings with latin-2 characters' do 'pół'.unpack('U*').should == [112, 243, 322] [112, 243, 322].pack('U*').unpack('U*').should == [112, 243, 322] end it 'correctly unpacks with c* strings with latin-2 characters' do 'ść'.unpack('c*').should == [-59, -101, -60, -121] end it 'correctly unpacks with s* binary strings' do "\xc8\x01".unpack('s*').should == [456] [678].pack('s').unpack('s').should == [678] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/each_byte_spec.rb
spec/opal/core/string/each_byte_spec.rb
require 'spec_helper' describe "String#each_byte" do it "get bytes from UTF-8 character (2 bytes)" do a = [] "ʆ".each_byte { |c| a << c } a.should == [202, 134] end it "get bytes from UTF-8 character (3 bytes)" do a = [] "ቜ".each_byte { |c| a << c } a.should == [225, 137, 156] end it "get bytes from UTF-8 emoji (4 bytes)" do a = [] "👋".each_byte { |c| a << c } a.should == [240, 159, 145, 139] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/to_sym_spec.rb
spec/opal/core/string/to_sym_spec.rb
# backtick_javascript: true require 'spec_helper' describe 'String#to_sym' do it 'returns a string literal' do str = "string" sym = str.to_sym `typeof(sym)`.should == 'string' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/string/scan_spec.rb
spec/opal/core/string/scan_spec.rb
describe 'String#scan' do it 'supports block argument destructuring' do foo = [] "/foo/:bar".scan(/:(\w+)/) { |name,| foo << name } foo.should == ["bar"] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/hash/internals_spec.rb
spec/opal/core/hash/internals_spec.rb
# backtick_javascript: true describe 'Hash' do describe 'internal implementation of string keys' do before :each do @h = {'a' => 123, 'b' => 456} end it 'stores keys directly as strings in the `Map`' do `#@h.size`.should == 2 `Array.from(#@h.keys())[0]`.should == 'a' `Array.from(#@h.keys())[1]`.should == 'b' @h['c'] = 789 `#@h.size`.should == 3 `Array.from(#@h.keys())[2]`.should == 'c' end it 'stores values directly as objects in the `Map`' do `Array.from(#@h.values()).length`.should == 2 `Array.from(#@h.values())[0]`.should == 123 `Array.from(#@h.values())[1]`.should == 456 @h['c'] = 789 `Array.from(#@h.values()).length`.should == 3 `Array.from(#@h.values())[2]`.should == 789 end it 'does not use the `Map.$$keys`' do `(#@h.$$keys === undefined)`.should == true @h['c'] = 789 `(#@h.$$keys === undefined)`.should == true end it 'uses the `Map.$$keys` object when an object key is added' do `(#@h.$$keys === undefined)`.should == true @h[Object.new] = 789 `#@h.$$keys.size`.should == 1 end it 'converts string objects to values when used to delete keys' do h = {'a' => 'a'} k = String.new(h.keys.first) h.delete(k) h.should == {} end end describe 'internal implementation of object keys' do before :each do @obj1 = Object.new @obj2 = Object.new @h = {@obj1 => 123, @obj2 => 456} end it 'uses a `Map.$$keys` to keep references of objects to be used as keys' do keys = `Array.from(#@h.$$keys.entries())` `#{keys}[0][1][0]`.should == @obj1 `#{keys}[0][0]`.should == @obj1.hash end it 'allows multiple keys that #hash to the same value to be stored in the Hash' do @hash = {} @mock1 = mock('mock1') @mock1.should_receive(:hash).at_least(1).and_return('hhh') @mock1.should_receive(:eql?).exactly(0) @mock2 = mock('mock2') @mock2.should_receive(:hash).at_least(1).and_return('hhh') @mock2.should_receive(:eql?).exactly(1).and_return(false) @mock3 = mock('mock3') @mock3.should_receive(:hash).at_least(1).and_return('hhh') @mock3.should_receive(:eql?).exactly(2).and_return(false) `#@hash.size`.should == 0 `(#@hash.$$keys === undefined)`.should == true @hash[@mock1] = 123 `#@hash.$$keys.size`.should == 1 keys = `Array.from(#@hash.$$keys.entries())` `#{keys}[0][1].length`.should == 1 `#{keys}[0][1][0]`.should == @mock1 `#{keys}[0][0]`.should == @mock1.hash `#@hash.get(#@mock1)`.should == 123 @hash[@mock2] = 456 `#@hash.$$keys.size`.should == 1 keys = `Array.from(#@hash.$$keys.entries())` `#{keys}[0][1].length`.should == 2 `#{keys}[0][1][1]`.should == @mock2 `#{keys}[0][0]`.should == @mock2.hash `#@hash.get(#@mock2)`.should == 456 @hash[@mock3] = 789 `#@hash.$$keys.size`.should == 1 keys = `Array.from(#@hash.$$keys.entries())` `#{keys}[0][1].length`.should == 3 `#{keys}[0][1][2]`.should == @mock3 `#{keys}[0][0]`.should == @mock3.hash `#@hash.get(#@mock3)`.should == 789 obj = Object.new @hash[obj] = 999 `#@hash.$$keys.size`.should == 2 keys = `Array.from(#@hash.$$keys.entries())` `#{keys}[1][1].length`.should == 1 `#{keys}[1][1][0]`.should == obj `#{keys}[1][0]`.should == obj.hash `#@hash.get(#{obj})`.should == 999 end it 'correctly updates internal data structures when deleting keys' do @mock1 = mock('mock1') @mock1.should_receive(:hash).any_number_of_times.and_return('hhh') @mock1.should_receive(:eql?).any_number_of_times.and_return(false) @mock2 = mock('mock2') @mock2.should_receive(:hash).any_number_of_times.and_return('hhh') @mock2.should_receive(:eql?).any_number_of_times.and_return(false) @mock3 = mock('mock3') @mock3.should_receive(:hash).any_number_of_times.and_return('hhh') @mock3.should_receive(:eql?).any_number_of_times.and_return(false) @mock4 = mock('mock4') @mock4.should_receive(:hash).any_number_of_times.and_return('hhh') @mock4.should_receive(:eql?).any_number_of_times.and_return(false) @hash = { @mock1 => 123, 'a' => 'abc', @mock2 => 456, 'b' => 'def', @mock3 => 789, @mock4 => 999, 'c' => 'ghi', @obj1 => 'xyz' } `#@hash.$$keys.has('hhh')`.should == true `#@hash.$$keys.has(#{@obj1.hash})`.should == true `#@hash.has('a')`.should == true `#@hash.has('b')`.should == true `#@hash.has('c')`.should == true `#@hash.size`.should == 8 `#@hash.$$keys.size`.should == 2 keys = `Array.from(#@hash.keys())` keys[0].should == @mock1 keys[1].should == 'a' keys[2].should == @mock2 keys[3].should == 'b' keys[4].should == @mock3 keys[5].should == @mock4 keys[6].should == 'c' keys[7].should == @obj1 keys = `Array.from(#@hash.$$keys.values())[0]` `#{keys}.length`.should == 4 keys[0].should == @mock1 keys[1].should == @mock2 keys[2].should == @mock3 keys[3].should == @mock4 keys = `Array.from(#@hash.$$keys.values())[1]` `#{keys}.length`.should == 1 keys[0].should == @obj1 @hash.delete @mock2 `#@hash.size`.should == 7 keys = `Array.from(#@hash.$$keys.values())[0]` `#{keys}.length`.should == 3 keys[0].should == @mock1 keys[1].should == @mock3 keys[2].should == @mock4 keys = `Array.from(#@hash.keys())` keys[0].should == @mock1 keys[1].should == 'a' keys[2].should == 'b' keys[3].should == @mock3 keys[4].should == @mock4 keys[5].should == 'c' keys[6].should == @obj1 @hash.delete @mock4 `#@hash.size`.should == 6 keys = `Array.from(#@hash.$$keys.values())[0]` `#{keys}.length`.should == 2 keys[0].should == @mock1 keys[1].should == @mock3 keys = `Array.from(#@hash.keys())` keys[0].should == @mock1 keys[1].should == 'a' keys[2].should == 'b' keys[3].should == @mock3 keys[4].should == 'c' keys[5].should == @obj1 @hash.delete @mock1 `#@hash.size`.should == 5 keys = `Array.from(#@hash.$$keys.values())[0]` `#{keys}.length`.should == 1 keys[0].should == @mock3 keys = `Array.from(#@hash.keys())` keys[0].should == 'a' keys[1].should == 'b' keys[2].should == @mock3 keys[3].should == 'c' keys[4].should == @obj1 @hash.delete @mock3 `#@hash.size`.should == 4 `#@hash.$$keys.size`.should == 1 keys = `Array.from(#@hash.$$keys.values())[0]` `#{keys}.length`.should == 1 keys[0].should == @obj1 keys = `Array.from(#@hash.keys())` keys[0].should == 'a' keys[1].should == 'b' keys[2].should == 'c' keys[3].should == @obj1 @hash.delete @obj1 `#@hash.size`.should == 3 `#@hash.$$keys.size`.should == 0 keys = `Array.from(#@hash.keys())` keys[0].should == 'a' keys[1].should == 'b' keys[2].should == 'c' `#@hash.$$keys.get(#{@obj1.hash}) === undefined`.should == true @hash.delete 'b' `#@hash.size`.should == 2 `#@hash.$$keys.size`.should == 0 keys = `Array.from(#@hash.keys())` keys[0].should == 'a' keys[1].should == 'c' `#@hash.get('a')`.should == 'abc' `#@hash.get('b') === undefined`.should == true `#@hash.get('c')`.should == 'ghi' @hash.delete 'c' `#@hash.size`.should == 1 `#@hash.$$keys.size`.should == 0 keys = `Array.from(#@hash.keys())` keys[0].should == 'a' `#@hash.get('a')`.should == 'abc' `#@hash.get('b') === undefined`.should == true `#@hash.get('c') === undefined`.should == true @hash.delete 'a' `#@hash.size`.should == 0 `#@hash.$$keys.size`.should == 0 `#@hash.get('a') === undefined`.should == true `#@hash.get('b') === undefined`.should == true `#@hash.get('c') === undefined`.should == true end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_with_dot/file 3.rb
spec/opal/core/fixtures/require_tree_with_dot/file 3.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_with_dot/index.rb
spec/opal/core/fixtures/require_tree_with_dot/index.rb
$ScratchPad << File.basename(__FILE__)+'-pre' require_tree '.' $ScratchPad << File.basename(__FILE__)+'-post'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_with_dot/file 1.rb
spec/opal/core/fixtures/require_tree_with_dot/file 1.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_with_dot/file 2.rb
spec/opal/core/fixtures/require_tree_with_dot/file 2.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/file 3.rb
spec/opal/core/fixtures/require_tree_files/file 3.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/file 1.rb
spec/opal/core/fixtures/require_tree_files/file 1.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/file 4.rb
spec/opal/core/fixtures/require_tree_files/file 4.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/file 2.rb
spec/opal/core/fixtures/require_tree_files/file 2.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/file 5.rb
spec/opal/core/fixtures/require_tree_files/file 5.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/nested/nested 2.rb
spec/opal/core/fixtures/require_tree_files/nested/nested 2.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/nested/nested 1.rb
spec/opal/core/fixtures/require_tree_files/nested/nested 1.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/fixtures/require_tree_files/other/other 1.rb
spec/opal/core/fixtures/require_tree_files/other/other 1.rb
$ScratchPad << File.basename(__FILE__)
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/methods_spec.rb
spec/opal/core/kernel/methods_spec.rb
module MethodsSpecs class Issue < Object def unique_method_name end end # Trigger stub generation Issue.new.unique_method_name end describe "Kernel#methods" do it "lists methods available on an object" do Object.new.methods.include?("puts").should == true end it "lists only singleton methods if false is passed" do o = Object.new def o.foo; 123; end o.methods(false).should == ["foo"] end it "ignores stub methods" do Object.methods.include?(:unique_method_name).should be_false end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/instance_variables_spec.rb
spec/opal/core/kernel/instance_variables_spec.rb
describe "Kernel#instance_variables" do context 'for nil' do it 'returns blank array' do expect(nil.instance_variables).to eq([]) end end context 'for string' do it 'returns blank array' do expect(''.instance_variables).to eq([]) end end context 'for non-empty string' do it 'returns blank array' do expect('test'.instance_variables).to eq([]) end end context 'for hash' do it 'returns blank array' do expect({}.instance_variables).to eq([]) end context 'for a hash with a default value' do it 'returns a blank array' do hash = Hash.new(0) expect(hash.instance_variables).to eq([]) end end context 'for a hash with a default proc' do it 'returns a blank array' do hash = Hash.new { 0 } expect(hash.instance_variables).to eq([]) end end end context 'for non-empty hash' do it 'returns blank array' do expect({ 1 => 2 }.instance_variables).to eq([]) end end context 'for array' do it 'returns blank array' do expect([].instance_variables).to eq([]) end end context 'for non-empty array' do it 'returns blank array' do expect((1..20).to_a.instance_variables).to eq([]) end end context 'for object' do it 'returns blank array' do expect(Object.new.instance_variables).to eq([]) end end context 'cloned object' do it 'returns same vars as source object' do object = Object.new expect(object.clone.instance_variables).to eq(object.instance_variables) end end context 'for object with js keyword as instance variables' do reserved_keywords = %w( @constructor @displayName @__proto__ @__parent__ @__noSuchMethod__ @__count__ @hasOwnProperty @valueOf ) reserved_keywords.each do |ivar| context "#{ivar} as instance variable name" do it "returns non-escaped #{ivar} in instance_variables list" do obj = Object.new obj.instance_variable_set(ivar, 'value') expect(obj.instance_variables).to eq([ivar]) end end end end context 'for a class' do it 'returns blank array' do expect(Class.new.instance_variables).to eq([]) end end context 'for a class with nested constant' do class ClassWithConstantWithoutIvar A = 1 end it 'returns blank array' do expect(ClassWithConstantWithoutIvar.instance_variables).to eq([]) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/puts_spec.rb
spec/opal/core/kernel/puts_spec.rb
describe "IO#puts" do before :each do @before_separator = $/ @io = IO.new(123) ScratchPad.record [] def @io.write(str) ScratchPad << str end end after :each do ScratchPad.clear @io.close if @io suppress_warning {$/ = @before_separator} end it "writes just a newline when given no args" do @io.puts.should == nil ScratchPad.recorded.join("").should == "\n" end it "writes just a newline when given just a newline" do @io.puts("\n").should == nil ScratchPad.recorded.should == ["\n"] end it "writes empty string with a newline when given nil as an arg" do @io.puts(nil).should == nil ScratchPad.recorded.join("").should == "\n" end it "writes empty string with a newline when when given nil as multiple args" do @io.puts(nil, nil).should == nil ScratchPad.recorded.join("").should == "\n\n" end it "calls :to_s before writing non-string objects that don't respond to :to_ary" do object = mock('hola') object.should_receive(:to_s).and_return("hola") @io.puts(object).should == nil ScratchPad.recorded.join("").should == "hola\n" end # it "returns general object info if :to_s does not return a string" do # object = mock('hola') # object.should_receive(:to_s).and_return(false) # # @io.puts(object).should == nil # ScratchPad.recorded.join("").should == object.inspect.split(" ")[0] + ">\n" # end it "writes each arg if given several" do @io.puts(1, "two", 3).should == nil ScratchPad.recorded.join("").should == "1\ntwo\n3\n" end it "flattens a nested array before writing it" do @io.puts([1, 2, [3]]).should == nil ScratchPad.recorded.join("").should == "1\n2\n3\n" end it "writes nothing for an empty array" do @io.puts([]).should == nil ScratchPad.recorded.should == [] end # it "writes [...] for a recursive array arg" do # x = [] # x << 2 << x # @io.puts(x).should == nil # ScratchPad.recorded.join("").should == "2\n[...]\n" # end it "writes a newline after objects that do not end in newlines" do @io.puts(5).should == nil ScratchPad.recorded.join("").should == "5\n" end it "does not write a newline after objects that end in newlines" do @io.puts("5\n").should == nil ScratchPad.recorded.join("").should == "5\n" end it "ignores the $/ separator global" do suppress_warning {$/ = ":"} @io.puts(5).should == nil ScratchPad.recorded.join("").should == "5\n" end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/require_tree_spec.rb
spec/opal/core/kernel/require_tree_spec.rb
describe 'Kernel.require_tree' do it 'loads all the files in a directory' do $ScratchPad = [] require_tree '../fixtures/require_tree_files' $ScratchPad.sort.should == ['file 1.rb', 'file 2.rb', 'file 3.rb', 'file 4.rb', 'file 5.rb', 'nested 1.rb', 'nested 2.rb', 'other 1.rb'] end it 'can be used with "."' do $ScratchPad = [] require_relative '../fixtures/require_tree_with_dot/index' $ScratchPad[0].should == 'index.rb-pre' $ScratchPad[1...-1].sort.should == ['file 1.rb', 'file 2.rb', 'file 3.rb'] $ScratchPad[-1].should == 'index.rb-post' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/at_exit_spec.rb
spec/opal/core/kernel/at_exit_spec.rb
# backtick_javascript: true module KernelExit extend self attr_accessor :status, :original_proc, :proc, :out self.original_proc = `Opal.exit` self.proc = `function(status){ #{KernelExit.status = `status`} }` def out_after_exit `Opal.exit = #{proc}` exit out ensure `Opal.exit = #{original_proc}` end def reset! self.out = [] end end describe "Kernel.at_exit" do before { KernelExit.reset! } def print(n) KernelExit.out << n end it "runs after all other code" do Kernel.at_exit {print 5} print 6 KernelExit.out_after_exit.should == [6,5] end it "runs in reverse order of registration" do at_exit {print 4} at_exit {print 5} print 6 at_exit {print 7} KernelExit.out_after_exit.should == [6,7,5,4] end it "allows calling exit inside at_exit handler" do at_exit {print 3} at_exit { print 4 exit # print 5 # This one is added to out because Opal.exit doesn't actually exit } at_exit {print 6} KernelExit.out_after_exit.should == [6,4,3] end # INCOMPLETE: the spec implementation is tricky here # it "gives access to the last raised exception" do # begin # at_exit do # print $!.message # end # raise 'foo' rescue nil # p [:err, $!] # rescue # end # # KernelExit.out_after_exit.should == ['foo'] # end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/respond_to_spec.rb
spec/opal/core/kernel/respond_to_spec.rb
# backtick_javascript: true class RespondToSpecs def foo end end describe "Kernel#respond_to?" do before :each do @a = RespondToSpecs.new end it "returns false if a method exists, but is marked with a '$$stub' property" do `#{@a}.$foo.$$stub = true` @a.respond_to?(:foo).should be_false end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/kernel/public_methods_spec.rb
spec/opal/core/kernel/public_methods_spec.rb
module PublicMethodsSpecs class Parent def parent_method end end class Child < Parent def child_method end end end describe "Kernel#public_methods" do it "lists methods available on an object" do child = PublicMethodsSpecs::Child.new child.public_methods.include?("parent_method").should == true child.public_methods.include?("child_method").should == true end it "lists only those methods in the receiver if false is passed" do child = PublicMethodsSpecs::Child.new def child.singular_method; 1123; end child.public_methods(false).sort.should == ["child_method", "singular_method"] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/struct/dup_spec.rb
spec/opal/core/struct/dup_spec.rb
describe "Struct#dup" do it "should return another struct instance" do klass = Struct.new("Klass", :foo) a = klass.new(1) b = a.dup b.foo = 2 a.foo.should == 1 b.foo.should == 2 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerator/with_index_spec.rb
spec/opal/core/enumerator/with_index_spec.rb
describe "Enumerator#with_index" do it "returns the result of the previously called method" do [1, 2, 3].each.with_index { |item, index| item * 2 }.should == [1, 2, 3] [1, 2, 3].map.with_index { |item, index| item * 2 }.should == [2, 4, 6] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/eval_spec.rb
spec/opal/core/runtime/eval_spec.rb
# backtick_javascript: true describe "Opal.eval()" do it "evaluates ruby code by compiling it to javascript and running" do `Opal['eval']("'foo'.class")`.should == String end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/exit_spec.rb
spec/opal/core/runtime/exit_spec.rb
# backtick_javascript: true describe "Exit (Kernel#exit / Opal.exit())" do it "forwards the status code to Opal.exit(status)" do received_status { Kernel.exit }.should == 0 received_status { Kernel.exit(0) }.should == 0 received_status { Kernel.exit(1) }.should == 1 received_status { Kernel.exit(2) }.should == 2 received_status { Kernel.exit(123) }.should == 123 received_status { Kernel.exit(true) }.should == 0 received_status { Kernel.exit(false) }.should == 1 lambda { received_status { Kernel.exit(Object.new) } }.should raise_error(TypeError) lambda { received_status { Kernel.exit([]) } }.should raise_error(TypeError) lambda { received_status { Kernel.exit(/123/) } }.should raise_error(TypeError) end def received_status received_status = nil original_exit = `Opal.exit` begin `Opal.exit = function(status) { #{received_status = `status`} }` yield ensure `Opal.exit = #{original_exit}` end received_status end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/string_spec.rb
spec/opal/core/runtime/string_spec.rb
# backtick_javascript: true require 'spec_helper' describe "Runtime String helpers" do context 'Opal.str' do it 'sets the encoding boxing literal strings' do -> { `Opal.str("foo", 'UTF-8')` }.should_not raise_error end end context 'Opal.set_encoding' do it 'sets the encoding for boxed strings' do expect(`Opal.set_encoding(new String("foo"), 'UTF-8')`.encoding).to eq(Encoding::UTF_8) expect(`Opal.set_encoding("foo".$dup(), 'UTF-8')`.encoding).to eq(Encoding::UTF_8) expect(`Opal.set_encoding("foo".$clone(), 'UTF-8')`.encoding).to eq(Encoding::UTF_8) end it 'raises FrozenError when provided a literal' do -> { `Opal.set_encoding("foo", 'UTF-8')` }.should raise_error(FrozenError) end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/main_methods_spec.rb
spec/opal/core/runtime/main_methods_spec.rb
require 'spec_helper' $OPAL_TOP_LEVEL_OBJECT = self def self.some_main_method 3.142 end def some_top_level_method_is_defined 42 end define_method :some_other_main_method do 0.1618 end describe "Defining normal methods at the top level" do it "should define them on Object, not main" do $OPAL_TOP_LEVEL_OBJECT.some_top_level_method_is_defined.should == 42 Object.new.some_top_level_method_is_defined.should == 42 end end describe "Defining singleton methods on main" do it "should define it on main directly" do $OPAL_TOP_LEVEL_OBJECT.some_main_method.should == 3.142 end it "should not define the method for all Objects" do lambda { Object.new.some_main_method }.should raise_error(NoMethodError) end end describe "Defining methods on main with define_method" do it "should define it on main directly" do $OPAL_TOP_LEVEL_OBJECT.some_other_main_method.should == 0.1618 Object.new.some_other_main_method.should == 0.1618 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/rescue_spec.rb
spec/opal/core/runtime/rescue_spec.rb
# backtick_javascript: true describe "The rescue keyword" do context 'Opal::Raw::Error' do it 'handles raw js throws' do begin `throw { message: 'foo' }` nil rescue Opal::Raw::Error => e e.JS[:message] end.should == 'foo' end it 'handles other Opal error' do begin raise 'bar' rescue Opal::Raw::Error => e e.message end.should == 'bar' end it 'can be combined with other classes to catch js errors' do begin `throw { message: 'baz' }` nil rescue Opal::Raw::Error, RuntimeError => e e.JS[:message] end.should == 'baz' end it 'can be combined with other classes to catch Opal errors' do begin raise 'quux' rescue Opal::Raw::Error, RuntimeError => e e.message end.should == 'quux' end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/truthy_spec.rb
spec/opal/core/runtime/truthy_spec.rb
# backtick_javascript: true class Boolean def self_as_an_object self end end class JsNil def <(other) `nil` end end describe "Opal truthyness" do it "should evaluate to true using js `true` as an object" do if true.self_as_an_object called = true end called.should be_true end it "should evaluate to false using js `false` as an object" do if false.self_as_an_object called = true end called.should be_nil end it "should evaluate to false if js `nil` is used with an operator" do is_falsey = JsNil.new < 2 ? false : true is_falsey.should be_true end it "should consider false, nil, null, and undefined as not truthy" do called = nil [`false`, `nil`, `null`, `undefined`].each do |v| if v called = true end end called.should be_nil end it "should true as truthy" do if `true` called = true end called.should be_true end it "should handle logic operators correctly for false, nil, null, and undefined" do (`false` || `nil` || `null` || `undefined` || 1).should == 1 [`false`, `nil`, `null`, `undefined`].each do |v| `#{1 && v} === #{v}`.should == true end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/is_a_spec.rb
spec/opal/core/runtime/is_a_spec.rb
# backtick_javascript: true describe 'Opal.is_a' do describe 'Numeric/Number special cases' do [ [1, :Numeric, true], [1, :Number, true], [1, :Fixnum, true], [1, :Integer, true], [1, :Float, true], [1.2, :Numeric, true], [1.2, :Number, true], [1.2, :Fixnum, true], [1.2, :Integer, false], [1.2, :Float, true], [Numeric.new, :Numeric, true], [Numeric.new, :Number, false], [Numeric.new, :Fixnum, false], [Numeric.new, :Integer, false], [Numeric.new, :Float, false], ].each do |(value, klass_name, result)| klass = Object.const_get(klass_name) it "returns #{result} for Opal.is_a(#{value}, #{klass_name})" do `Opal.is_a(#{value}, #{klass})`.should == result end end it 'can rely on Number subclasses having $$is_number_class on their prototype' do `!!#{Numeric}.$$is_number_class`.should == false `!!#{Number}.$$is_number_class`.should == true `!!#{Fixnum}.$$is_number_class`.should == true `!!#{Integer}.$$is_number_class`.should == true `!!#{Float}.$$is_number_class`.should == true end it 'can rely on Number subclasses having $$is_integer_class on their prototype' do `!!#{Numeric}.$$is_integer_class`.should == false `!!#{Number}.$$is_integer_class`.should == false `!!#{Fixnum}.$$is_integer_class`.should == false `!!#{Integer}.$$is_integer_class`.should == true `!!#{Float}.$$is_integer_class`.should == false end it 'works for non-Opal objects' do `Opal.is_a({}, Opal.Array)`.should == false end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/method_missing_spec.rb
spec/opal/core/runtime/method_missing_spec.rb
# backtick_javascript: true require "spec_helper" module MethodMissingSpecs class A def method_missing(mid, *args) [mid, args] end end class B def method_missing(mid, *args, &block) [mid, block] end end end class BridgedClass < `(function NativeConstructor(){})` end describe "method_missing" do before do @obj = MethodMissingSpecs::A.new end it "should pass the missing method name as first argument" do @obj.foo.should == [:foo, []] end it "should correctly pass arguments to method_missing" do @obj.bar(1, 2, 3).should == [:bar, [1, 2, 3]] end it "calls method missing for operators" do obj = Object.new obj.should_receive(:method_missing).with(:+, 123).and_return(42) (obj + 123).should == 42 end it "should pass blocks to method_missing" do obj = MethodMissingSpecs::B.new proc = proc { 1 } obj.baz(1, 2, &proc).should == [:baz, proc] end end describe "BasicObject#method_missing" do it "raises an error for the missing method" do lambda { BasicObject.new.foo_bar_baz }.should raise_error(Exception) end end describe "Array#method_missing" do it "raises an error for the missing method" do lambda { BasicObject.new.foo_bar_baz }.should raise_error(Exception) end end describe "<BridgedClass>#method_missing" do it "raises an error for the missing method" do lambda { BridgedClass.new.foo_bar_baz }.should raise_error(Exception) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/bridged_classes_spec.rb
spec/opal/core/runtime/bridged_classes_spec.rb
# backtick_javascript: true require 'spec_helper' %x{ var bridge_class_demo = function(){}; bridge_class_demo.prototype.$foo = function() { return "bar" }; } class TopBridgedClassDemo < `bridge_class_demo` def some_bridged_method [1, 2, 3] end def method_missing(name, *args, &block) return :catched if name == :catched_by_method_missing super end end describe "Bridged Classes" do describe "Passing native constructor to class keyword" do before do @bridged = ::TopBridgedClassDemo @instance = `new bridge_class_demo()` end it "should expose the given class at the top level scope" do @bridged.should be_kind_of(Class) end it "gives the class the correct name" do @bridged.name.should == "TopBridgedClassDemo" end it "should have all BasicObject methods defined" do @instance.should respond_to(:instance_eval) @bridged.new.should respond_to(:==) end it "should have all Object methods defined" do @instance.should respond_to(:class) @bridged.new.should respond_to(:singleton_class) end it "instances of class should be able to call native ruby methods" do @instance.foo.should == "bar" @bridged.new.foo.should == "bar" end it "allows new methods to be defined on the bridged prototype" do @instance.some_bridged_method.should == [1, 2, 3] @bridged.new.some_bridged_method.should == [1, 2, 3] end end describe ".instance_methdods" do it "should report methods for class" do Array.instance_methods(false).should include(:shift) end it "should not include methods donated from Object/Kernel" do Array.instance_methods(false).should_not include(:class) end it "should not include methods donated from BasicObject" do Array.instance_methods(false).should_not include(:__send__) Array.instance_methods(false).should_not include(:send) end end describe '#method_missing' do it 'works' do lambda { @instance.not_catched_by_method_missing }.should raise_error(NoMethodError) @instance.catched_by_method_missing.should == :catched end end end class ModularizedBridgeClass def something 'different module' end end %x{ var bridge_class_demo_module = function(){}; bridge_class_demo_module.prototype.$foo = function() { return "foobar" }; } module BridgeModule class ModularizedBridgeClass < `bridge_class_demo_module` def some_bridged_method [4, 5, 6] end end end describe 'Bridged classes in different modules' do before do @bridged = BridgeModule::ModularizedBridgeClass @instance = `new bridge_class_demo_module()` end it "should expose the given class not at the top level scope" do @bridged.should be_kind_of(Class) end it 'should not disturb an existing class at the top level scope' do ModularizedBridgeClass.new.something.should == 'different module' end it "gives the class the correct name" do @bridged.name.should == "BridgeModule::ModularizedBridgeClass" end it "instances of class should be able to call native ruby methods" do @instance.foo.should == "foobar" @bridged.new.foo.should == "foobar" end it "allows new methods to be defined on the bridged prototype" do @instance.some_bridged_method.should == [4, 5, 6] @bridged.new.some_bridged_method.should == [4, 5, 6] end end %x{ var counter = 0; var reset_counter = function() { counter = 0; }; var bridge_class_with_constructor = function() { counter++; }; } class BridgedLevel0 < `bridge_class_with_constructor`; end class BridgedLevel1 < BridgedLevel0; end class BridgedLevel2 < BridgedLevel1; end class BridgedLevel3 < BridgedLevel2; end describe 'Inheritance with bridged classes' do it 'should call a JS constructor on level 0' do `reset_counter()` BridgedLevel0.new `counter`.should == 1 end it 'should call a JS constructor on level 1' do `reset_counter()` BridgedLevel1.new `counter`.should == 1 end it 'should call a JS constructor on level 2' do `reset_counter()` BridgedLevel2.new `counter`.should == 1 end it 'should call a JS constructor on level 3' do `reset_counter()` BridgedLevel3.new `counter`.should == 1 end end describe 'Invalid bridged classes' do it 'raises a TypeError when trying to extend with non-Class' do error_msg = /superclass must be a Class/ -> { class TestClass < `""`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < `3`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < `true`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < `Math`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < `Object.create({})`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < `Object.create(null)`; end }.should raise_error(TypeError, error_msg) -> { class TestClass < Module.new; end }.should raise_error(TypeError, error_msg) -> { class TestClass < BasicObject.new; end }.should raise_error(TypeError, error_msg) end end describe 'Bridging subclassed JavaScript Classes' do it 'is working' do %x{ class Dog { bark() { return 'wuff'; }} class ChowChow extends Dog { cuddle() { return 'grrrrr'; }} } class ChowChow < `ChowChow` def bark `self.bark()` end def cuddle `self.cuddle()` end end # check direct bridge ChowChow.new.cuddle.should == 'grrrrr' # check if js superclass can be reached ChowChow.new.bark.should == 'wuff' end it 'is kinda working with subclassed bridged classes' do # Lets demonstrate how that works for a simple case: # JS class inheriting from bridged JS class: %x{ class SuperString extends String { constructor(arg) { super(arg); } travel_through_time() { return 'Hello my dear friend! Greetings from the future!'; } } } # build bridge: class RubySuperString < `SuperString` def travel_through_time `self.travel_through_time()` end def incinerate '' end end # this does work: RubySuperString.new.travel_through_time.should == 'Hello my dear friend! Greetings from the future!' # this does work too: RubySuperString.new.incinerate == '' # that too: %x{ function try_access_from_javascript() { try { return (new SuperString()).$incinerate(); } catch { return nil; } } } `try_access_from_javascript()`.should == '' # We inherited from JS String which has ::String in its prototype, can we slice? RubySuperString.new('123').slice(0, 9).should == "undefined" # Of course not, a bit weird. One must take care of such things when bridging. # The standard Object allocator ignores args. Usually they are handled in #initialize. # But we must pass the arg when allocating the object so we must overwrite ::new : class RubySuperString def self.new(arg) `new self.$$constructor(arg)` end end # can we now slice? RubySuperString.new('123').slice(1).should == '2' # Yes. Nice. But note that this is a Method from ::String! # The availablity of methods from another class may come as a surprise when bridging # Classes with bridges in its prototype chain. # But did we mess up prototypes? Can String maybe #travel_through_time too? -> { String.new.travel_through_time.should == 'Hello my dear friend! Greetings from the future!' }.should raise_error NoMethodError # No. Phuu. # For more complicated cases "manually" adapting the protype chain may be required. # But we don't need to test that, because we assume that people know what they # are doing when they adapt prototypes. end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/loaded_spec.rb
spec/opal/core/runtime/loaded_spec.rb
# backtick_javascript: true describe 'Opal.loaded' do before do %w[foo bar baz].each do |module_name| `delete Opal.require_table[#{module_name}]` `Opal.loaded_features.splice(Opal.loaded_features.indexOf(#{module_name}))` end end it 'it works with multiple paths' do `Opal.loaded(['bar'])` `(Opal.require_table.foo == null)`.should == true `(Opal.require_table.bar === true)`.should == true `(Opal.require_table.baz == null)`.should == true `Opal.loaded(['foo', 'bar', 'baz'])` `(Opal.require_table.foo === true)`.should == true `(Opal.require_table.bar === true)`.should == true `(Opal.require_table.baz === true)`.should == true end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/runtime/constants_spec.rb
spec/opal/core/runtime/constants_spec.rb
# backtick_javascript: true module RuntimeFixtures class A end class A::B module C end end module ModuleB end module ModuleA include ModuleB end end describe "Constants access via .$$ with dots (regression for #1418)" do it "allows to acces scopes on `Opal`" do `Opal.Object.$$.RuntimeFixtures.$$.A.$$.B.$$.C`.should == RuntimeFixtures::A::B::C end end describe "Inclusion of modules" do it "that have been included by other modules works" do # here ClassC would have failed to be created due to a bug in Opal.append_features module RuntimeFixtures class ClassC include ModuleA include ModuleB end end RuntimeFixtures::ClassC.new.class.should == RuntimeFixtures::ClassC end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/find_index_break_spec.rb
spec/opal/core/enumerable/find_index_break_spec.rb
describe "Enumerable#find_index" do it "breaks out with the proper value" do [1, 2, 3].find_index { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/each_slice_break_spec.rb
spec/opal/core/enumerable/each_slice_break_spec.rb
describe "Enumerable#each_slice" do it "breaks out with the proper value" do [1, 2, 3].each_slice(1) { break 42 }.should == 42 [1, 2, 3].each_slice(2) { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/one_break_spec.rb
spec/opal/core/enumerable/one_break_spec.rb
describe "Enumerable#one?" do it "breaks out with the proper value" do [1, 2, 3].one? { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/max_by_break_spec.rb
spec/opal/core/enumerable/max_by_break_spec.rb
describe "Enumerable#max_by" do it "breaks out with the proper value" do [1, 2, 3].max_by { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/min_break_spec.rb
spec/opal/core/enumerable/min_break_spec.rb
describe "Enumerable#min" do it "breaks out with the proper value" do [1, 2, 3].min { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/count_break_spec.rb
spec/opal/core/enumerable/count_break_spec.rb
describe "Enumerable#count" do it "breaks out with the proper value" do [1, 2, 3].count { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/reduce_break_spec.rb
spec/opal/core/enumerable/reduce_break_spec.rb
describe "Enumerable#reduce" do it "breaks out with the proper value" do [1, 2, 3].reduce { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/max_break_spec.rb
spec/opal/core/enumerable/max_break_spec.rb
describe "Enumerable#max" do it "breaks out with the proper value" do [1, 2, 3].max { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/collect_break_spec.rb
spec/opal/core/enumerable/collect_break_spec.rb
describe "Enumerable#collect" do class Test include Enumerable def each(&block) [1, 2, 3].each(&block) end end it "breaks out with the proper value" do Test.new.collect { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/any_break_spec.rb
spec/opal/core/enumerable/any_break_spec.rb
describe "Enumerable#any?" do it "breaks out with the proper value" do [1, 2, 3].any? { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/each_with_index_break_spec.rb
spec/opal/core/enumerable/each_with_index_break_spec.rb
describe "Enumerable#each_with_index" do it "breaks out with the proper value" do [1, 2, 3].each_with_index { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/grep_break_spec.rb
spec/opal/core/enumerable/grep_break_spec.rb
describe "Enumerable#grep" do it "breaks out with the proper value" do [1, 2, 3].grep(1) { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/take_while_break_spec.rb
spec/opal/core/enumerable/take_while_break_spec.rb
describe "Enumerable#take_while" do it "breaks out with the proper value" do [1, 2, 3].take_while { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/drop_while_break_spec.rb
spec/opal/core/enumerable/drop_while_break_spec.rb
describe "Enumerable#drop_while" do it "breaks out with the proper value" do [1, 2, 3].drop_while { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/all_break_spec.rb
spec/opal/core/enumerable/all_break_spec.rb
describe "Enumerable#all?" do it "breaks out with the proper value" do [1, 2, 3].all? { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/find_all_break_spec.rb
spec/opal/core/enumerable/find_all_break_spec.rb
describe "Enumerable#find_all" do it "breaks out with the proper value" do [1, 2, 3].find_all { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/none_break_spec.rb
spec/opal/core/enumerable/none_break_spec.rb
describe "Enumerable#none?" do it "breaks out with the proper value" do [1, 2, 3].none? { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/min_by_break_spec.rb
spec/opal/core/enumerable/min_by_break_spec.rb
describe "Enumerable#min_by" do it "breaks out with the proper value" do [1, 2, 3].min_by { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/each_with_object_break_spec.rb
spec/opal/core/enumerable/each_with_object_break_spec.rb
describe "Enumerable#each_with_object" do it "breaks out with the proper value" do [1, 2, 3].each_with_object(23) { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/enumerable/detect_break_spec.rb
spec/opal/core/enumerable/detect_break_spec.rb
describe "Enumerable#detect" do it "breaks out with the proper value" do [1, 2, 3].detect { break 42 }.should == 42 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/regexp/match_spec.rb
spec/opal/core/regexp/match_spec.rb
# backtick_javascript: true describe 'Regexp#match' do describe 'when pos is not specified' do it 'calls .exec only once on the current object' do regexp = /test/ calls = 0 %x( regexp._exec = regexp.exec; regexp.exec = function(str) { var match = this._exec(str); calls++; return match; } ) result = regexp.match('test test') calls.should == 1 result.begin(0).should == 0 result[0].should == 'test' end end describe 'when pos is specified' do it 'does not call .exec on the current object' do regexp = /test/ calls = 0 %x( regexp._exec = regexp.exec; regexp.exec = function(str) { var match = this._exec(str); calls++; return match; } ) result = regexp.match('test test', 1) calls.should == 0 result[0].should == 'test' result.begin(0).should == 5 end end end describe 'Regexp#match?' do describe 'when pos is not specified' do it 'calls .test on the current object' do regexp = /test/ calls = 0 %x( regexp._test = regexp.test; regexp.test = function(str) { var verdict = this._test(str); calls++; return verdict; } ) result = regexp.match?('test test') calls.should == 1 result.should == true end end describe 'when pos is specified' do it 'does not call .test on the current object' do regexp = /test/ calls = 0 %x( regexp._test = regexp.test; regexp.test = function(str) { var verdict = this._test(str); calls++; return verdict; } ) result = regexp.match?('test test', 1) calls.should == 0 # FIXME pos is not yet supported by Opal's Regexp#match? #result.should == true end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/regexp/interpolation_spec.rb
spec/opal/core/regexp/interpolation_spec.rb
describe 'Regexp interpolation' do it 'can interpolate other regexps' do a = /a/ /#{a}/.should =~ 'aaa' /a+/.should =~ 'aaa' /#{a}+/.should =~ 'aaa' /aa/.should =~ 'aaa' /#{a}a/.should =~ 'aaa' end it 'can interpolate objects' do a = Object.new def a.to_s; 'a'; end /#{a}/.should =~ 'aaa' /a+/.should =~ 'aaa' /#{a}+/.should =~ 'aaa' /aa/.should =~ 'aaa' /#{a}a/.should =~ 'aaa' end it 'can interpolate strings' do a = 'a' /#{a}/.should =~ 'aaa' /a+/.should =~ 'aaa' /#{a}+/.should =~ 'aaa' /aa/.should =~ 'aaa' /#{a}a/.should =~ 'aaa' end it 'can interpolate string literals' do /#{'a'}/.should =~ 'aaa' /a+/.should =~ 'aaa' /#{'a'}+/.should =~ 'aaa' /aa/.should =~ 'aaa' /#{'a'}a/.should =~ 'aaa' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/regexp/assertions_spec.rb
spec/opal/core/regexp/assertions_spec.rb
describe 'Regexp assertions' do it 'matches the beginning of input' do /\Atext/.should =~ 'text' /\Atext/.should_not =~ 'the text' regexp = Regexp.new('\Atext') regexp.should =~ 'text' regexp.should_not =~ 'the text' end it 'matches the end of input' do /text\z/.should =~ 'the text' /text\z/.should_not =~ 'text of' regexp = Regexp.new('text\z') regexp.should =~ 'the text' regexp.should_not =~ 'text of' end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/marshal/load_spec.rb
spec/opal/core/marshal/load_spec.rb
describe "Marshal.load" do it 'loads array with instance variable' do a = Marshal.load("\x04\bI[\bi\x06i\ai\b\x06:\n@ivari\x01{") a.should == [1, 2, 3] a.instance_variable_get(:@ivar).should == 123 end it 'loads a hash with a default value (hash_def)' do hash = Marshal.load("\x04\b}\x06i\x06i\a:\bdef") hash.should == { 1 => 2 } hash.default.should == :def end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/marshal/dump_spec.rb
spec/opal/core/marshal/dump_spec.rb
# encoding: binary require 'spec_helper' module MarshalExtension end class MarshalUserRegexp < Regexp end class UserMarshal attr_reader :data def initialize @data = 'stuff' end def marshal_dump() 'data' end def marshal_load(data) @data = data end def ==(other) self.class === other and @data == other.data end end describe 'Marshal.dump' do it 'dumps non-empty Array' do expect(Marshal.dump(['a', 1, 2])).to eq("\u0004\b[\b\"\u0006ai\u0006i\a") end it 'dumps case-sensitive regexp' do expect(Marshal.dump(/\w+/)).to eq("\u0004\b/\b\\w+\u0000") end it 'dumps case-insensitive regexp' do expect(Marshal.dump(/\w+/i)).to eq("\u0004\b/\b\\w+\u0001") end it "dumps a Float" do Marshal.dump(123.4567).should == "\004\bf\r123.4567" Marshal.dump(-0.841).should == "\x04\bf\v-0.841" Marshal.dump(9876.345).should == "\004\bf\r9876.345" Marshal.dump(Float::INFINITY).should == "\004\bf\binf" Marshal.dump(-Float::INFINITY).should == "\004\bf\t-inf" Marshal.dump(Float::NAN).should == "\004\bf\bnan" end it "dumps a Integer" do Marshal.dump(0).should == "\x04\bi\x00" Marshal.dump(123).should == "\x04\bi\x01{" Marshal.dump(-123).should == "\x04\bi\x80" Marshal.dump(1234567890).should == "\x04\bl+\a\xD2\x02\x96I" Marshal.dump(-1234567890).should == "\x04\bl-\a\xD2\x02\x96I" end it "dumps a Regexp with flags" do Marshal.dump(/\w/im).should == "\x04\b/\a\\w\u0005" end it 'dumps an extended Regexp' do Marshal.dump(/\w/.extend(MarshalExtension)).should == "\x04\be:\u0015MarshalExtension/\a\\w\u0000" end it 'dumps object#marshal_dump when object responds to #marshal_dump' do Marshal.dump(UserMarshal.new).should == "\u0004\bU:\u0010UserMarshal\"\tdata" end it 'saves a link to an object before processing its instance variables' do top = Object.new ref = Object.new a = Object.new b = Object.new c = Object.new top.instance_variable_set(:@a, a) top.instance_variable_set(:@b, b) top.instance_variable_set(:@a, c) top.instance_variable_set(:@ref, ref) expected = "\u0004\b[\ao:\vObject\b:\a@ao:\vObject\u0000:\a@bo:\vObject\u0000:\t@refo:\vObject\u0000@\t" Marshal.dump([top, ref]).should == expected loaded = Marshal.load(expected) loaded[0].instance_variable_get(:@ref).object_id.should == loaded[1].object_id end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/union_spec.rb
spec/opal/core/array/union_spec.rb
describe "Array#|" do it "relies on Ruby's #hash (not JavaScript's #toString) for identifying array items" do a1 = [ 123, '123'] a2 = ['123', 123 ] (a1 | a2).should == a1 (a2 | a1).should == a2 a1 = [ Time.at(1429521600.1), Time.at(1429521600.9) ] a2 = [ Time.at(1429521600.9), Time.at(1429521600.1) ] (a1 | a2).should == a1 (a2 | a1).should == a2 a1 = [ Object.new, Object.new ] a2 = [ Object.new, Object.new ] (a1 | a2).should == a1 + a2 (a2 | a1).should == a2 + a1 a1 = [ 1, 2, 3, '1', '2', '3'] a2 = ['1', '2', '3', 1, 2, 3 ] (a1 | a2).should == a1 (a2 | a1).should == a2 a1 = [ [1, 2, 3], '1,2,3'] a2 = ['1,2,3', [1, 2, 3] ] (a1 | a2).should == a1 (a2 | a1).should == a2 a1 = [ true, 'true'] a2 = ['true', true ] (a1 | a2).should == a1 (a2 | a1).should == a2 a1 = [ false, 'false'] a2 = ['false', false ] (a1 | a2).should == a1 (a2 | a1).should == a2 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/include_spec.rb
spec/opal/core/array/include_spec.rb
# backtick_javascript: true describe "Array#include" do it "should respect nil values" do nileq = Object.new def nileq.==(other) nil end [nileq].should_not include("no match expected") end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/dup_spec.rb
spec/opal/core/array/dup_spec.rb
# backtick_javascript: true describe "Array#dup" do it "should use slice optimization" do a = Array.new `a.slice = function() { return ['sliced'] }` lambda { a.dup }.should_not raise_error a.dup.should == ['sliced'] end it "should use slice optimization on Array subclass" do subclass = Class.new(Array) a = subclass.new `a.slice = function() { return ['sliced'] }` lambda { a.dup }.should_not raise_error a.dup.should == ['sliced'] end it "should not use slice optimization when allocation is redefined" do subclass = Class.new(Array) a = subclass.new subclass.define_singleton_method(:allocate) { raise 'Overriden method, no slice optimization for you!' } lambda { a.dup }.should raise_error # dup should call allocate because the method is overriden end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/zip_spec.rb
spec/opal/core/array/zip_spec.rb
describe "Array#zip" do it "respects block arity" do foo = ['A', 'B'] values = [] foo.zip(foo) do | a,b | values << [a, b] end values.should == [['A', 'A'], ['B', 'B']] end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/minus_spec.rb
spec/opal/core/array/minus_spec.rb
describe "Array#-" do it "relies on Ruby's #hash (not JavaScript's #toString) for identifying array items" do a1 = [ 123 ] a2 = ['123'] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ Time.at(1429521600.1) ] a2 = [ Time.at(1429521600.9) ] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ Object.new ] a2 = [ Object.new ] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ 1, 2, 3 ] a2 = ['1', '2', '3'] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ 1, 2, 3 ] a2 = ['1,2,3'] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ true ] a2 = ['true'] (a1 - a2).should == a1 (a2 - a1).should == a2 a1 = [ false ] a2 = ['false'] (a1 - a2).should == a1 (a2 - a1).should == a2 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/uniq_spec.rb
spec/opal/core/array/uniq_spec.rb
describe "Array#uniq" do it "relies on Ruby's #hash (not JavaScript's #toString) for identifying array items" do a = [ 123, '123'] a.uniq.should == a a = [ Time.at(1429521600.1), Time.at(1429521600.9) ] a.uniq.should == a a = [ Object.new, Object.new ] a.uniq.should == a a = [ 1, 2, 3, '1', '2', '3'] a.uniq.should == a a = [ [1, 2, 3], '1,2,3'] a.uniq.should == a a = [ true, 'true'] a.uniq.should == a a = [ false, 'false'] a.uniq.should == a end end describe "Array#uniq!" do it "relies on Ruby's #hash (not JavaScript's #toString) for identifying array items" do a = [ 123, '123'] a.uniq!.should == nil a = [ Time.at(1429521600.1), Time.at(1429521600.9) ] a.uniq!.should == nil a = [ Object.new, Object.new ] a.uniq!.should == nil a = [ 1, 2, 3, '1', '2', '3'] a.uniq!.should == nil a = [ [1, 2, 3], '1,2,3'] a.uniq!.should == nil a = [ true, 'true'] a.uniq!.should == nil a = [ false, 'false'] a.uniq!.should == nil end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/spec/opal/core/array/compact_spec.rb
spec/opal/core/array/compact_spec.rb
# backtick_javascript: true describe "Array#compact" do it "compacts nil and JavaScript null and undefined" do a = [1, nil, `null`, `undefined`] expect(a.size).to eq 4 expect(a.compact.size).to eq 1 a.compact! expect(a.size).to eq 1 end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false