简体   繁体   中英

Why does my Ruby test return only one word instead of the entire auth_name string?

Here is the code I have:

def initialize (htaccess_file_content)
   @htaccess_hash = Hash.new
   htaccess_file_content.each_line do | line |
      @commands = line.split
      @htaccess_hash[@commands[0]] = @commands[1]
   end
end
def auth_name
  @htaccess_hash['AuthName'].gsub(/''/,"")
end

This is my spec:

describe WebServer::Htaccess do
  let(:auth_name) { "This is the auth_name" }
end

describe '#auth_name' do
  it 'returns the AuthName string' do
    expect(htaccess_user.auth_name).to eq auth_name
  end
end

My Ruby code is not returning the whole string and I don't know why. Here is the error message from the failed test:

 Failure/Error: expect(htaccess_user.auth_name).to eq auth_name

   expected: "This is the auth_name"
        got: "\"This"

   (compared using ==)

Use an Array Slice

@htaccess_hash[@commands[0]] = @commands[1]

String#split splits on whitespace by default, so when you specify @commands[1] you are assigning only a single array element (the word "This") as your hash value. The simplest thing you can do is to change your subscript to an Array#slice to assign all the remaining elements as the hash value, eg:

@commands = line.split
@htaccess_hash[@commands[0]] = @commands[1..-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM