获取NameError:使用rspec测试实例变量时,不允许使用`format'作为实例变量名

Hom*_*ith 17 ruby rspec

我有以下测试:

let(:client) { Descat::Client.new }

describe 'poblacio' do
  it 'should set format correctly' do
    client.poblacio('v1','json','dades')
    expect (client.instance_variable_get(:format)).to eq('json')
  end
end
Run Code Online (Sandbox Code Playgroud)

我有以下正在测试的代码:

module Descat
  class Client
    BASE_URL = 'http://api.idescat.cat/'

    def initialize(attributes = {})
      attributes.each do |attr, value|
        self.send("#{attr}=", value)
      end
    end

    def poblacio(version, format, operation, *args)
      @format = format
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

运行测试我一直在'

Failure/Error: expect (client.instance_variable_get(:format)).to eq('json')
     NameError:
Run Code Online (Sandbox Code Playgroud)

但是,更改名称并没有帮助.

"

mec*_*ish 38

要使用instance_variable_get你必须提供以...开头的名称"@".在你的情况下:

client.instance_variable_get('@format')
Run Code Online (Sandbox Code Playgroud)

  • 或`client.instance_variable_get(:@ format)` (2认同)