初始化项中的RSpec双/模拟实例变量



我有一个类,在初始化器中,我需要从解析的参数中调用实例变量:

class PrintResults
include SortResults
attr_accessor :views_hash
def initialize(parser)
@parser = parser
@views_hash = parser.page_views
end

我想测试属性访问者,我尝试了以下内容:

RSpec.describe PrintResults do
subject { described_class.new(views_hash) }
describe 'attributes accessors' do
let(:accessors) { double(page_views: { '/that_70s_show' => ['111.111.111.111'] }) }
it 'should have views hash' do
subject.views_hash = accessors
expect(subject.views_hash).to eq(['111.111.111.111'])
end
end

但是我得到了一个错误:

1) PrintResults attributes accessors should have views hash
Failure/Error: expect(subject.views_hash).to eq(['111.111.111.111'])
expected: ["111.111.111.111"]
got: #<Double (anonymous)>
(compared using ==)
Diff:
@@ -1 +1 @@
-["111.111.111.111"]
+#<Double (anonymous)>

您将测试double直接分配给返回的属性,而不是使用initialize方法。

代替

subject { described_class.new(views_hash) }
describe 'attributes accessors' do
let(:accessors) { double(page_views: { '/that_70s_show' => ['111.111.111.111'] }) }
it 'should have views hash' do
subject.views_hash = accessors
expect(subject.views_hash).to eq(['111.111.111.111'])
end
end

使用

subject { described_class.new(parser) }
describe 'attributes accessors' do
let(:parser) { double(page_views: { '/that_70s_show' => ['111.111.111.111'] }) }
it 'should have views hash' do
expect(subject.views_hash).to eq('/that_70s_show' => ['111.111.111.111'])
end
end

相关内容

  • 没有找到相关文章

最新更新