LoginSignup
1

More than 5 years have passed since last update.

Rspecでundefined method `proxy_for' for nil:NilClassが起きたら

Posted at

久しぶりにRspecでテストを書いたらタイトルのエラーに遭遇した。
proxy周りなんて触ってないのになんで・・・?と思い調べたところ、とても初歩的なミスだった。

結論は以下の参考サイトに挙がっている通り。
#it#identifyブロックの外で#stub#should_receiveを書いていたのが原因だった。

書いたテストはこんな感じ。
#describe直下の#stubがまずい。

describe MyClass1 do
  before { @my_instance = MyClass1.new }

  describe "#my_method" do
    MyClass2.stub(:my_method).and_return(true)

    expect(@my_instance.my_method).to be_true
  end
end

実行するとこんなエラーが出る

$GEM_HOME/gems/rspec-mocks-2.14.4/lib/rspec/mocks.rb:26:in `proxy_for': undefined method `proxy_for' for nil:NilClass (NoMethodError)
        from $GEM_HOME/gems/rspec-mocks-2.14.4/lib/rspec/mocks.rb:51:in `allow_message'
        from $GEM_HOME/gems/rspec-mocks-2.14.4/lib/rspec/mocks/syntax.rb:19:in `stub_object'
        from $GEM_HOME/gems/rspec-mocks-2.14.4/lib/rspec/mocks/syntax.rb:40:in `stub'

コードの良し悪しは別として、こんな感じに直せばOK

describe MyClass1 do
  before { @my_instance = MyClass1.new }

  describe "#my_method" do
    it "should be success" do
      MyClass2.stub(:my_method).and_return(true)

      expect(@my_instance.my_method).to be_true
    end
  end
end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1