Skip to content

Commit

Permalink
Supports Rails 4.1 inversible associations
Browse files Browse the repository at this point in the history
  • Loading branch information
alindeman committed Dec 28, 2013
1 parent 463fd18 commit 0e52280
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/rspec/rails/mocks.rb
Expand Up @@ -29,6 +29,19 @@ def respond_to?(message, include_private=false)
end
end

# Starting with Rails 4.1, ActiveRecord associations are inversible
# by default. This class represents an association from the mocked
# model's perspective.
#
# @private
class Association
attr_accessor :target, :inversed

def initialize(association_name)
@association_name = association_name
end
end

module ActiveRecordInstanceMethods
# Stubs `persisted?` to return `false` and `id` to return `nil`.
def destroy
Expand All @@ -45,6 +58,15 @@ def [](key)
def new_record?
!persisted?
end

# Returns an object representing an association from the mocked
# model's perspective. For use by Rails internally only.
def association(association_name)
unless defined?(@associations)
@associations = Hash.new { |h, k| h[k] = Association.new(k) }
end
@associations[association_name]
end
end

# Creates a test double representing `string_or_model_class` with common
Expand Down
23 changes: 23 additions & 0 deletions spec/rspec/rails/mocks/mock_model_spec.rb
Expand Up @@ -54,6 +54,29 @@
end
end

describe "association" do
it "constructs a mock association object" do
model = mock_model(MockableModel)
expect(model.association(:association_name)).to be
end

it "returns a different association object for each association name" do
model = mock_model(MockableModel)
posts = model.association(:posts)
authors = model.association(:authors)

expect(posts).not_to equal(authors)
end

it "returns the same association model each time for the same association name" do
model = mock_model(MockableModel)
posts1 = model.association(:posts)
posts2 = model.association(:posts)

expect(posts1).to equal(posts2)
end
end

describe "errors" do
context "default" do
it "is empty" do
Expand Down

0 comments on commit 0e52280

Please sign in to comment.