@@ -286,6 +286,105 @@ class AssociationClass
286286 end
287287 end
288288
289+ describe ".find_by!" do
290+ context "when record exists with the specified attribute value" do
291+ it "returns the record" do
292+ record1 = DummyClass . record ( id : 1 ) do |r |
293+ r . name = "foo"
294+ end
295+ _record2 = DummyClass . record ( id : 2 ) do |r |
296+ r . name = "bar"
297+ end
298+
299+ found_record = DummyClass . find_by! ( name : "foo" )
300+
301+ expect ( found_record ) . to eq ( record1 )
302+ end
303+ end
304+
305+ context "when no record exists that matches the specified attribute value" do
306+ it "raises exception" do
307+ DummyClass . record ( id : 1 ) do |r |
308+ r . name = "foo"
309+ end
310+
311+ expect {
312+ DummyClass . find_by! ( name : "bar" )
313+ } . to raise_error (
314+ StaticAssociation ::RecordNotFound ,
315+ "Couldn't find DummyClass with name=bar"
316+ )
317+ end
318+ end
319+
320+ context "when multiple records match the specified attribute value" do
321+ it "returns the first matching record" do
322+ record1 = DummyClass . record ( id : 1 ) do |r |
323+ r . name = "foo"
324+ end
325+ _record2 = DummyClass . record ( id : 2 ) do |r |
326+ r . name = "foo"
327+ end
328+
329+ found_record = DummyClass . find_by! ( name : "foo" )
330+
331+ expect ( found_record ) . to eq ( record1 )
332+ end
333+ end
334+
335+ context "when specifying multiple attribute values" do
336+ it "returns the record matching all attributes" do
337+ _record1 = DummyClass . record ( id : 1 ) do |r |
338+ r . name = "foo"
339+ end
340+ record2 = DummyClass . record ( id : 2 ) do |r |
341+ r . name = "foo"
342+ end
343+
344+ found_record = DummyClass . find_by! ( id : 2 , name : "foo" )
345+
346+ expect ( found_record ) . to eq ( record2 )
347+ end
348+ end
349+
350+ context "when specifying multiple attribute values but no record " \
351+ "matches all attributes" do
352+ it "returns nil" do
353+ _record1 = DummyClass . record ( id : 1 ) do |r |
354+ r . name = "foo"
355+ end
356+
357+ expect {
358+ DummyClass . find_by! ( id : 1 , name : "bar" )
359+ } . to raise_error (
360+ StaticAssociation ::RecordNotFound ,
361+ "Couldn't find DummyClass with id=1, name=bar"
362+ )
363+ end
364+ end
365+
366+ context "with undefined attributes" do
367+ it "raises a StaticAssociation::UndefinedAttribute" do
368+ DummyClass . record ( id : 1 )
369+
370+ expect {
371+ DummyClass . find_by! ( undefined_attribute : 1 )
372+ } . to raise_error (
373+ StaticAssociation ::UndefinedAttribute ,
374+ "Undefined attribute 'undefined_attribute'"
375+ )
376+ end
377+ end
378+
379+ context "with no attributes" do
380+ it "raises a StaticAssociation::ArgumentError" do
381+ expect {
382+ DummyClass . find_by!
383+ } . to raise_error ( StaticAssociation ::ArgumentError )
384+ end
385+ end
386+ end
387+
289388 describe ".belongs_to_static" do
290389 it "defines a reader method for the association" do
291390 associated_class = AssociationClass . new
0 commit comments