首页 > 解决方案 > 如何在 Rspec 中为哈希创建模拟

问题描述

我是日本人。对不起,英语很丑。

我想创建哈希模拟。

所以,我试试这段代码,

但发生错误

To allow expectations on `nil` and suppress this message, set `RSpec::Mocks.configuration.allow_message_expectations_on_nil` to `true`. To disallow expectations on `nil`, set `RSpec::Mocks.configuration.allow_message_expectations_on_nil` to `false`. 

有没有别的写法?请教我。

AppointmentRank.new(
            id: appointment.id,
            name: @rank[appointment.rank_id]
          )

@rank是哈希。

rspec

let(:rank){{ 1 => 'S', 2 => 'A', 3 => 'B' }}
let(:rank_id){2}

allow(@rank).to receive(:[]).with(rank_id).and_return('A')

标签: ruby-on-railsrubyrspec

解决方案


问题是它let不会创建实例变量

您的let行创建了名为并且在您的测试中可用的方法:rankrank_id

RSpec.describe "let behavior" do
  let(:rank){{ 1 => 'S', 2 => 'A', 3 => 'B' }}
  let(:rank_id){2}

  it "defines a method not an instance variable" do
    expect(@rank).to be_nil
    expect(rank).to be_a Hash
  end
end

所以换句话说,除非你定义它们,否则不要在你的测试中使用@rankor 。@rank_id使用rankandrank_id代替

Ruby 中的实例变量如果未声明,则为 nil。这就是为什么它不会引发错误 call @rank,即使它实际上是未定义的。


推荐阅读