@@ -137,4 +137,100 @@ def metadata(source)
137137 ) . to eq ( "{#{ expected_symbol } , #{ expected_special } , #{ expected_focus } }" )
138138 end
139139 end
140+
141+ describe '#inside_class_method?' do
142+ def example_group_hook ( source )
143+ RuboCop ::RSpec ::ExampleGroup . new ( parse_source ( source ) . ast ) . hooks . first
144+ end
145+
146+ it 'returns true if the hook is in class method' do
147+ expect (
148+ example_group_hook (
149+ 'describe Foo { def self.setup; before { do_something }; end }'
150+ ) . inside_class_method?
151+ ) . to be ( true )
152+ end
153+
154+ it 'returns true if the hook is in class << self method' do
155+ source = <<~RUBY
156+ describe Foo do
157+ class << self
158+ def setup
159+ before { do_something }
160+ end
161+ end
162+ end
163+ RUBY
164+ expect ( example_group_hook ( source ) . inside_class_method? ) . to be ( true )
165+ end
166+
167+ it 'returns true if the hook is in method in multiline class << self' do
168+ source = <<~RUBY
169+ describe Foo do
170+ class << self
171+ other_code
172+
173+ def setup
174+ before { do_something }
175+ end
176+ end
177+ end
178+ RUBY
179+ expect ( example_group_hook ( source ) . inside_class_method? ) . to be ( true )
180+ end
181+
182+ it 'returns false if the hook is in instance method' do
183+ expect (
184+ example_group_hook (
185+ 'describe Foo { def setup; before { do_something }; end }'
186+ ) . inside_class_method?
187+ ) . to be ( false )
188+ end
189+
190+ it 'returns false if the hook is in instance method of multiline class' do
191+ source = <<~RUBY
192+ describe Foo do
193+ other_code
194+
195+ def setup
196+ before { do_something }
197+ end
198+ end
199+ RUBY
200+ expect ( example_group_hook ( source ) . inside_class_method? ) . to be ( false )
201+ end
202+
203+ it 'returns false if the hook is in in method in global scope' do
204+ expect (
205+ example_group_hook (
206+ 'def setup; before { do_something }; end'
207+ ) . inside_class_method?
208+ ) . to be ( false )
209+ end
210+
211+ it 'returns false if the hook is in multiline global scope' do
212+ source = <<~RUBY
213+ other_code
214+
215+ def setup
216+ before { do_something }
217+ end
218+ RUBY
219+ expect ( example_group_hook ( source ) . inside_class_method? ) . to be ( false )
220+ end
221+
222+ it 'returns false if the hook is in example group body' do
223+ expect (
224+ example_group_hook (
225+ 'describe Foo { before { do_something } }'
226+ ) . inside_class_method?
227+ ) . to be ( false )
228+ end
229+
230+ it 'returns false if the hook is in global scope' do
231+ expect (
232+ hook ( 'before { do_something }' ) . inside_class_method?
233+ ) . to be ( false )
234+ end
235+ end
140236end
0 commit comments