Skip to content

Instantly share code, notes, and snippets.

@mark-d-holmberg
Forked from pauljamesrussell/spec_helper.rb
Last active December 25, 2015 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark-d-holmberg/6996941 to your computer and use it in GitHub Desktop.
Save mark-d-holmberg/6996941 to your computer and use it in GitHub Desktop.
Allows it to test accepts_nested_attributes_for with associations that are a `has_one`
# See: https://gist.github.com/1353500
# Use: it { should accept_nested_attributes_for(:association_name).using_has_one(true).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
# Let us use has_one associations
model.send("#{association}").clear unless @using_has_one
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
chain :using_has_one do |using_has_one|
@using_has_one = using_has_one
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment