LoginSignup
16
2

More than 3 years have passed since last update.

RSpecで変更が無い事を確認しようとしたらLint/AmbiguousBlockAssociationというLintエラーが発生した

Last updated at Posted at 2019-06-06

テスト自体は通っていたが、プルリクを出す前にRuboCopを動かして検証したところ、Lint/AmbiguousBlockAssociationという以下のLintエラーが発生した。

Lint/AmbiguousBlockAssociation: Parenthesize the param change{ analysis.foo_count } to make sure that the block will be associated with the change method call.

該当のspecファイルの記述抜粋(一部、実態のコードから変更)
require 'rails_helper'

RSpec.describe Dummy, type: :model do
  describe '.method' do
    subject { Dummy.method!(foo_analysis: analysis, foo_data: foo_data) }
    let(:analysis) { create :users_foo_analysis }
    context 'when foo_data is empty' do
      let(:foo_data) { [].to_json }
      it { is_expected.to eq Dummy.none }
      it { expect { subject }.to_not change{ analysis.foo_count } }
    end

動作しない前提で、試しに以下のように変更をかけてテストを動作させてみた。

変更前
■変更箇所
 it { expect { subject }.to_not change{ analysis.foo_count } }
変更後
 it { expect { subject }.to_not change analysis.foo_count }

すると、以下のようなエラーが表示された。

ArgumentError:
  `change` requires either an object and message (`change(obj, :msg)`) or a block (`change { }`). You passed an object but no message.

(change { })の形式ではRuboCopに怒られてしまっていたので、(change(obj, :msg))の形式に修正した形でテストを通しつつ、RuboCopに怒られないようにするためにどうすれば良いか調査してみた。

結論、以下のような記述であれば、テストを通しつつ、RuboCopに怒られずにすんだ。

最終形
  it { expect { subject }.to_not change(analysis, :foo_count) }

change(obj, :msg)の:msgって何だろう?と戸惑ったが、普通にメソッドを渡せば動きそうだなと思い、試しにやってみたら上手くいった。

:msgとかではなく、もっと分かりやすいエラーメッセージなら素早く解決できたのに。。。。

16
2
1

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
16
2