Last active
June 8, 2017 11:11
-
-
Save CharlieHawker/e466dc88c0b2875e02c8e9f04757dab8 to your computer and use it in GitHub Desktop.
RSpec matchers for direct assignment of attributes to an object
This file contains hidden or 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
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