在使用浏览器 gem 的 class 的 RSpec 测试中出现名称错误(未定义的局部变量 'browser')
Name error (undefined local variable 'browser') in an RSpec test for a class that uses the Browser gem
我有一个 class 用于通过从 post 请求中获取一部分参数并向它们添加一些用户代理信息来构造一些用户参数。为此,我正在使用 browser gem。
gem 添加了一个名为浏览器的辅助方法,用于检查您当前的用户代理。它的使用就这么简单:
require "browser"
browser.name # readable browser name
browser.version # major version number
我的一小部分 class 看起来像这样:
class AkUserParams
def self.create(params)
@user_params = params[:signature]
@user_params[:user_agent] = browser.user_agent
@user_params
end
end
在我的整个应用程序中使用浏览器 gem 工作正常。但是,当我在 RSpec 中为 class 编写规范时,出现以下错误:
NameError: undefined local variable or method 'browser' for AkUserParams:Class
describe AkUserParams do
# I have tried both with and without this before block:
before :all do
$browser = Browser.new
end
let(:some_params) {{
signature: {
name: Faker::Name.name,
email: Faker::Internet.email,
}
}}
# This is a bogus test I'm expecting to fail. It doesn't get to
# failing and instead gives me a name error.
it 'Builds an object containing data about the user and the action' do
expect(AkUserParams.create(petition_signature)).to eq(true)
end
end
更新:我通过注入 browser
:
解决了这个问题
class AkUserParams
def self.create(browser, params)
@user_params = params[:signature]
@user_params[:user_agent] = browser.user_agent
@user_params
end
end
这样我就可以 let(:browser) { Browser.new }
在规范中。
我有一个 class 用于通过从 post 请求中获取一部分参数并向它们添加一些用户代理信息来构造一些用户参数。为此,我正在使用 browser gem。
gem 添加了一个名为浏览器的辅助方法,用于检查您当前的用户代理。它的使用就这么简单:
require "browser"
browser.name # readable browser name
browser.version # major version number
我的一小部分 class 看起来像这样:
class AkUserParams
def self.create(params)
@user_params = params[:signature]
@user_params[:user_agent] = browser.user_agent
@user_params
end
end
在我的整个应用程序中使用浏览器 gem 工作正常。但是,当我在 RSpec 中为 class 编写规范时,出现以下错误:
NameError: undefined local variable or method 'browser' for AkUserParams:Class
describe AkUserParams do
# I have tried both with and without this before block:
before :all do
$browser = Browser.new
end
let(:some_params) {{
signature: {
name: Faker::Name.name,
email: Faker::Internet.email,
}
}}
# This is a bogus test I'm expecting to fail. It doesn't get to
# failing and instead gives me a name error.
it 'Builds an object containing data about the user and the action' do
expect(AkUserParams.create(petition_signature)).to eq(true)
end
end
更新:我通过注入 browser
:
class AkUserParams
def self.create(browser, params)
@user_params = params[:signature]
@user_params[:user_agent] = browser.user_agent
@user_params
end
end
这样我就可以 let(:browser) { Browser.new }
在规范中。