Created
July 8, 2010 03:26
-
-
Save bcardarella/467607 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mongoid association matchers for RSpec 2.x and 1.x | |
# | |
# Save this file to your spec/support directory | |
# | |
# Usage: | |
# | |
# describe User do | |
# it { should reference_one :profile } | |
# end | |
# | |
# describe Profile do | |
# it { should be_referenced_in :user } | |
# end | |
module Matchers | |
module Mongoid | |
module Associations | |
def reference_one(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::ReferencesOne) | |
end | |
def reference_many(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::ReferencesMany) | |
end | |
def be_referenced_in(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::ReferencedIn) | |
end | |
def embed_one(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::EmbedsOne) | |
end | |
def embed_many(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::EmbedMany) | |
end | |
def be_embedded_in(attr) | |
AssociationMatcher.new(attr, ::Mongoid::Associations::EmbeddedIn) | |
end | |
class AssociationMatcher | |
attr_accessor :attr, :association_type | |
def initialize(attr, association_type) | |
self.attr = attr.to_s | |
self.association_type = association_type | |
end | |
def matches?(subject) | |
@subject = subject | |
a = @subject.associations.select { |k,v| v.association == association_type } | |
a.detect { |k| k.first == attr } != nil | |
end | |
def description | |
"has #{humanized_association} association :#{attr}" | |
end | |
def failure_message_for_should | |
"\n#{humanized_association} association failure\nExpected: '#{attr}'" | |
end | |
private | |
def humanized_association | |
association_type.to_s.split('::').last | |
end | |
end | |
end | |
end | |
end | |
if defined?(RSpec) # RSpec 2.x | |
RSpec.configure do |config| | |
config.include(Matchers::Mongoid::Associations) | |
end | |
elsif defined?(Spec) # RSpec 1.x | |
Spec::Runner.configure do |config| | |
config.include(Matchers::Mongoid::Associations) | |
end | |
end |
Cool! If you have anything please let me know and I might be able to use it and contribute to it as well. I was in the process of starting this already.
I should have something by this weekend. I'll ping you when ready.
Might want to check out http://github.com/evansagge/mongoid-rspec.git
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jeroenvandijk already working on it