Created
November 9, 2011 23:15
-
-
Save pauljamesrussell/1353500 to your computer and use it in GitHub Desktop.
RSpec matcher for ensuring a model is accepting nested attributes for an association, and accepting/rejecting the right values.
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
# Use: it { should accept_nested_attributes_for(:association_name).and_accept({valid_values => true}).but_reject({ :reject_if_nil => nil })} | |
RSpec::Matchers.define :accept_nested_attributes_for do |association| | |
match do |model| | |
@model = model | |
@nested_att_present = model.respond_to?("#{association}_attributes=".to_sym) | |
if @nested_att_present && @reject | |
model.send("#{association}_attributes=".to_sym,[@reject]) | |
@reject_success = model.send("#{association}").empty? | |
end | |
model.send("#{association}").clear | |
if @nested_att_present && @accept | |
model.send("#{association}_attributes=".to_sym,[@accept]) | |
@accept_success = ! (model.send("#{association}").empty?) | |
end | |
@nested_att_present && ( @reject.nil? || @reject_success ) && ( @accept.nil? || @accept_success ) | |
end | |
failure_message_for_should do | |
messages = [] | |
messages << "accept nested attributes for #{association}" unless @nested_att_present | |
messages << "reject values #{@reject.inspect} for association #{association}" unless @reject_success | |
messages << "accept values #{@accept.inspect} for association #{association}" unless @accept_success | |
"expected #{@model.class} to " + messages.join(", ") | |
end | |
description do | |
desc = "accept nested attributes for #{expected}" | |
if @reject | |
desc << ", but reject if attributes are #{@reject.inspect}" | |
end | |
end | |
chain :but_reject do |reject| | |
@reject = reject | |
end | |
chain :and_accept do |accept| | |
@accept = accept | |
end | |
end |
@pauljamesrussell maybe you should do a pull request to the shoulda macros to use your features for rejection?
+1 for @andreorvalho. cc @pauljamesrussell.
Hi @pauljamesrussell, shout out from 2023 :). I have a v6.0 for shoulda-matchers, but get this error: NoMethodError: undefined method 'but_reject' for #<Shoulda::Matchers::ActiveRecord::AcceptNestedAttributesForMatcher:0x0000561601c0e078>
. Could you please recommend what to do?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@JohnSmall - I believe the Shoulda macros do not support the reject_if: option.