Michael Fellinger
3/2/2009 10:34:00 AM
On Mon, Mar 2, 2009 at 6:49 PM, Sarah Allen <sarah@ultrasaurus.com> wrote:
> I'm probably missing some basic Ruby syntax, but I'm relatively new to
> Ruby and can't figure this out from the various references I've looked
> at
>
> I'd like to use this nifty test helper:
>
> =C2=A0# Calls creation_method with nil values for field_names and asserts
> that
> =C2=A0# the resulting object was not saved and that errors were added for
> that field.
> =C2=A0#
> =C2=A0# =C2=A0assert_required_fields :create_article, :subject, :body, :a=
uthor
> =C2=A0def assert_required_fields(creation_method, *field_names)
> =C2=A0 =C2=A0field_names.each do |field|
> =C2=A0 =C2=A0 =C2=A0record =3D send(creation_method, field =3D> nil)
> =C2=A0 =C2=A0 =C2=A0assert_equal false, record.valid?
> =C2=A0 =C2=A0 =C2=A0assert_not_nil record.errors.on(field)
> =C2=A0 =C2=A0end
> =C2=A0end
## Using blocks:
def assert_required_fields(*field_names, &block)
field_names.each do |field_name|
record =3D yield(field_name =3D> nil)
assert_equal(false, record.valid?)
assert_not_nil(record.errors.on(field)
end
end
# Usage:
assert_required_fields(:email, :lastname, :password){|field|
User::create(field) }
## Using the method itself
def assert_required_fields(method, *field_names)
field_names.each do |field_name|
record =3D method.call(field_name =3D> nil)
assert_equal(false, record.valid?)
assert_not_nil(record.errors.on(field)
end
end
# Usage
assert_required_fields(User.method(:create), :email, :lastname, :password)
## Using send
def assert_required_fields(obj, method, *field_names)
field_names.each do |field_name|
record =3D obj.send(method, field_name =3D> nil)
assert_equal(false, record.valid?)
assert_not_nil(record.errors.on(field)
end
end
# Usage
assert_required_fields(User, :create, :email, :lastname, :password)
^ manveru