|
| 1 | +require_relative '../spec_helper' |
| 2 | + |
| 3 | +ruby_version_is "3.4" do |
| 4 | + describe "The `it` parameter" do |
| 5 | + it "provides it in a block" do |
| 6 | + -> { it }.call("a").should == "a" |
| 7 | + proc { it }.call("a").should == "a" |
| 8 | + lambda { it }.call("a").should == "a" |
| 9 | + ["a"].map { it }.should == ["a"] |
| 10 | + end |
| 11 | + |
| 12 | + it "assigns nil to not passed parameters" do |
| 13 | + proc { it }.call().should == nil |
| 14 | + end |
| 15 | + |
| 16 | + it "can be used in both outer and nested blocks at the same time" do |
| 17 | + -> { it + -> { it * it }.call(2) }.call(3).should == 7 |
| 18 | + end |
| 19 | + |
| 20 | + it "is a regular local variable if there is already a 'it' local variable" do |
| 21 | + it = 0 |
| 22 | + proc { it }.call("a").should == 0 |
| 23 | + end |
| 24 | + |
| 25 | + it "raises SyntaxError when block parameters are specified explicitly" do |
| 26 | + -> { eval("-> () { it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 27 | + -> { eval("-> (x) { it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 28 | + |
| 29 | + -> { eval("proc { || it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 30 | + -> { eval("proc { |x| it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 31 | + |
| 32 | + -> { eval("lambda { || it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 33 | + -> { eval("lambda { |x| it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 34 | + |
| 35 | + -> { eval("['a'].map { || it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 36 | + -> { eval("['a'].map { |x| it }") }.should raise_error(SyntaxError, /ordinary parameter is defined/) |
| 37 | + end |
| 38 | + |
| 39 | + it "affects block arity" do |
| 40 | + -> {}.arity.should == 0 |
| 41 | + -> { it }.arity.should == 1 |
| 42 | + end |
| 43 | + |
| 44 | + it "affects block parameters" do |
| 45 | + -> { it }.parameters.should == [[:req]] |
| 46 | + |
| 47 | + ruby_version_is ""..."4.0" do |
| 48 | + proc { it }.parameters.should == [[:opt, nil]] |
| 49 | + end |
| 50 | + ruby_version_is "4.0" do |
| 51 | + proc { it }.parameters.should == [[:opt]] |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + it "does not affect binding local variables" do |
| 56 | + -> { it; binding.local_variables }.call("a").should == [] |
| 57 | + end |
| 58 | + |
| 59 | + it "does not work in methods" do |
| 60 | + obj = Object.new |
| 61 | + def obj.foo; it; end |
| 62 | + |
| 63 | + -> { obj.foo("a") }.should raise_error(ArgumentError, /wrong number of arguments/) |
| 64 | + end |
| 65 | + end |
| 66 | +end |
0 commit comments