summaryrefslogtreecommitdiff
path: root/spec/ruby/core/string/delete_prefix_spec.rb
blob: bd5b56a312bff47af97ff3db9f66a70dec55fcf1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- encoding: utf-8 -*-
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "String#delete_prefix" do
  it "returns a copy of the string, with the given prefix removed" do
    'hello'.delete_prefix('hell').should == 'o'
    'hello'.delete_prefix('hello').should == ''
  end

  it "returns a copy of the string, when the prefix isn't found" do
    s = 'hello'
    r = s.delete_prefix('hello!')
    r.should_not equal s
    r.should == s
    r = s.delete_prefix('ell')
    r.should_not equal s
    r.should == s
    r = s.delete_prefix('')
    r.should_not equal s
    r.should == s
  end

  ruby_version_is ''...'2.7' do
    it "taints resulting strings when other is tainted" do
      'hello'.taint.delete_prefix('hell').should.tainted?
      'hello'.taint.delete_prefix('').should.tainted?
    end
  end

  it "doesn't set $~" do
    $~ = nil

    'hello'.delete_prefix('hell')
    $~.should == nil
  end

  it "calls to_str on its argument" do
    o = mock('x')
    o.should_receive(:to_str).and_return 'hell'
    'hello'.delete_prefix(o).should == 'o'
  end

  it "returns a subclass instance when called on a subclass instance" do
    s = StringSpecs::MyString.new('hello')
    s.delete_prefix('hell').should be_an_instance_of(StringSpecs::MyString)
  end
end

describe "String#delete_prefix!" do
  it "removes the found prefix" do
    s = 'hello'
    s.delete_prefix!('hell').should equal(s)
    s.should == 'o'
  end

  it "returns nil if no change is made" do
    s = 'hello'
    s.delete_prefix!('ell').should == nil
    s.delete_prefix!('').should == nil
  end

  it "doesn't set $~" do
    $~ = nil

    'hello'.delete_prefix!('hell')
    $~.should == nil
  end

  it "calls to_str on its argument" do
    o = mock('x')
    o.should_receive(:to_str).and_return 'hell'
    'hello'.delete_prefix!(o).should == 'o'
  end

  it "raises a FrozenError when self is frozen" do
    -> { 'hello'.freeze.delete_prefix!('hell') }.should raise_error(FrozenError)
    -> { 'hello'.freeze.delete_prefix!('') }.should raise_error(FrozenError)
    -> { ''.freeze.delete_prefix!('') }.should raise_error(FrozenError)
  end
end