Permalink
Browse files

Supports Rails 4.1 inversible associations

  • Loading branch information...
1 parent d66d178 commit 70edf9689a4905120a8ce4b31a11cd1841e11634 @alindeman alindeman committed Dec 27, 2013
Showing with 45 additions and 0 deletions.
  1. +22 −0 lib/rspec/rails/mocks.rb
  2. +23 −0 spec/rspec/rails/mocks/mock_model_spec.rb
View
@@ -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
@@ -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
@@ -53,6 +53,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

0 comments on commit 70edf96

Please sign in to comment.