Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails 4 Postgresql store accessor matcher
module Shoulda
module Matchers
module ActiveRecord
def have_store_accessor(key)
HaveStoreAccessor.new(key)
end
class HaveStoreAccessor
def initialize(key)
@key = key
@options = {}
end
def within(store_attribute)
@options[:store_attribute] = store_attribute
self
end
def matches?(subject)
@subject = subject
key_accessor_exists? && correct_store?
end
def description
desc = "have store accessor named #{@key}"
desc << " within the #{@options[:store_attribute]}" if @options.key?(:store_attribute)
end
def failure_message_for_should
"Expected #{expectation} (#{@missing})"
end
def failure_message_for_should_not
"Did not expect #{expectation}"
end
protected
def key_accessor_exists?
if @subject.respond_to?(@key) && @subject.respond_to?("#{@key}=")
true
else
@missing = "#{@subject.class} does not have a store accessor named #{@key}"
end
end
def correct_store?
return true unless @options.key?(:store_attribute)
@subject.send(:"#{@key}=", '1')
val = @subject.send(@key)
val == '1' && @subject.send(@options[:store_attribute])[@key] == val
rescue
false
end
def expectation
expected = "#{@subject.class} to #{description}"
end
end
end
end
end
@antoniosb

This comment has been minimized.

Copy link

@antoniosb antoniosb commented Feb 24, 2015

I'm getting a deprecation warning from RSpec 3.2.0. To remove I've just renamed the methods failure_message_for_should and failure_message_for_should_not into failure_message and failure_message_when_negated respectively. Btw, thanks a lot for this gist, great job!

@zpieslak

This comment has been minimized.

Copy link

@zpieslak zpieslak commented Aug 13, 2015

Maybe I'm missing something but key_accessor_exists? will always return true...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment