Skip to content

Instantly share code, notes, and snippets.

@CharlieHawker
Last active June 8, 2017 11:11
Show Gist options
  • Save CharlieHawker/e466dc88c0b2875e02c8e9f04757dab8 to your computer and use it in GitHub Desktop.
Save CharlieHawker/e466dc88c0b2875e02c8e9f04757dab8 to your computer and use it in GitHub Desktop.
RSpec matchers for direct assignment of attributes to an object
module DirectAssignmentMatchers
require 'rspec/expectations'
RSpec::Matchers.define :prevent_direct_assignment_of do |attribute|
match do |object|
!DirectAssignmentMatchers::public_assign(object, attribute)
end
end
RSpec::Matchers.define :allow_direct_assignment_of do |attribute|
match do |object|
!!DirectAssignmentMatchers::public_assign(object, attribute)
end
end
private
def self.public_assign(object, attribute)
begin
object.public_send(:"#{attribute.to_s}=", 'test')
true
rescue NoMethodError
false
end
end
end
RSpec.configure do |config|
config.include DirectAssignmentMatchers
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment