File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed
lib/active_record/relation Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -123,6 +123,11 @@ def first(*args)
123123 end
124124 end
125125
126+ # Same as #first! but raises RecordNotFound if no record is returned
127+ def first! ( *args )
128+ self . first ( *args ) or raise RecordNotFound
129+ end
130+
126131 # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
127132 # same arguments to this method as you can to <tt>find(:last)</tt>.
128133 def last ( *args )
@@ -137,6 +142,11 @@ def last(*args)
137142 end
138143 end
139144
145+ # Same as #last! but raises RecordNotFound if no record is returned
146+ def last! ( *args )
147+ self . last ( *args ) or raise RecordNotFound
148+ end
149+
140150 # A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
141151 # same arguments to this method as you can to <tt>find(:all)</tt>.
142152 def all ( *args )
Original file line number Diff line number Diff line change @@ -191,6 +191,30 @@ def test_first_failing
191191 assert_nil Topic . where ( "title = 'The Second Topic of the day!'" ) . first
192192 end
193193
194+ def test_first_bang_present
195+ assert_nothing_raised do
196+ assert_equal topics ( :second ) , Topic . where ( "title = 'The Second Topic of the day'" ) . first!
197+ end
198+ end
199+
200+ def test_first_bang_missing
201+ assert_raises ActiveRecord ::RecordNotFound do
202+ Topic . where ( "title = 'This title does not exist'" ) . first!
203+ end
204+ end
205+
206+ def test_last_bang_present
207+ assert_nothing_raised do
208+ assert_equal topics ( :second ) , Topic . where ( "title = 'The Second Topic of the day'" ) . last!
209+ end
210+ end
211+
212+ def test_last_bang_missing
213+ assert_raises ActiveRecord ::RecordNotFound do
214+ Topic . where ( "title = 'This title does not exist'" ) . last!
215+ end
216+ end
217+
194218 def test_unexisting_record_exception_handling
195219 assert_raise ( ActiveRecord ::RecordNotFound ) {
196220 Topic . find ( 1 ) . parent
You can’t perform that action at this time.
0 commit comments