Skip to content

Commit b8ff930

Browse files
committed
Add support for active record read_attribute public method
1 parent 748032c commit b8ff930

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

lib/rspec/active_model/mocks/mocks.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ def [](key)
6161
# alternative to record['id']
6262
alias_method :_read_attribute, :[]
6363

64+
# Rails>7.1 added read_attribute for external usage similar to record['id']
65+
alias_method :read_attribute, :[]
66+
6467
# Returns the opposite of `persisted?`
6568
def new_record?
6669
!persisted?

spec/rspec/active_model/mocks/mock_model_spec.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,44 @@ def self.===(_other)
482482
end
483483
end
484484

485+
describe "attribute access methods" do
486+
it "supports [] method with symbol" do
487+
model = mock_model(MockableModel, :name => "John", :age => 25)
488+
expect(model[:name]).to eq("John")
489+
expect(model[:age]).to eq(25)
490+
end
491+
492+
it "supports [] method with string" do
493+
model = mock_model(MockableModel, :name => "John", :age => 25)
494+
expect(model["name"]).to eq("John")
495+
expect(model["age"]).to eq(25)
496+
end
497+
498+
it "supports read_attribute method with symbol" do
499+
model = mock_model(MockableModel, :name => "John", :age => 25)
500+
expect(model.read_attribute(:name)).to eq("John")
501+
expect(model.read_attribute(:age)).to eq(25)
502+
end
503+
504+
it "supports read_attribute method with string" do
505+
model = mock_model(MockableModel, :name => "John", :age => 25)
506+
expect(model.read_attribute("name")).to eq("John")
507+
expect(model.read_attribute("age")).to eq(25)
508+
end
509+
510+
it "supports _read_attribute method with symbol" do
511+
model = mock_model(MockableModel, :name => "John", :age => 25)
512+
expect(model._read_attribute(:name)).to eq("John")
513+
expect(model._read_attribute(:age)).to eq(25)
514+
end
515+
516+
it "supports _read_attribute method with string" do
517+
model = mock_model(MockableModel, :name => "John", :age => 25)
518+
expect(model._read_attribute("name")).to eq("John")
519+
expect(model._read_attribute("age")).to eq(25)
520+
end
521+
end
522+
485523
describe "ActiveModel Lint tests" do
486524
# rubocop:disable Lint/EmptyExpression,Metrics/BlockNesting
487525
begin

0 commit comments

Comments
 (0)