Skip to content

#47 Ensure that the attribute's default value is set correctly. Examples... #95

Closed
wants to merge 1 commit into from

3 participants

@dlupu
dlupu commented Apr 11, 2012

...:

it { should have_a_default.for(:count) }
it { should have_a_default.of(0).for(:count) }
it { should default_to(0).on_the(:count).column }

For more information, read the comments :)

@dlupu dlupu #47 Ensure that the attribute's default value is set correctly. Examp…
…les:

it { should have_a_default.for(:count) }
it { should have_a_default.of(0).for(:count) }
it { should default_to(0).on_the(:count).column }

For more information, read the comments :)
6ae941b
@dlupu
dlupu commented Apr 11, 2012

This is a new pull request, as agreed on #47

@gabebw gabebw commented on the diff Apr 13, 2012
...oulda/matchers/active_model/have_a_default_matcher.rb
+
+ def for(attribute)
+ @attribute = attribute
+ self
+ end
+ alias :on_the :for
+
+ def column
+ self #syntactic sugar
+ end
+ alias :attribute :column
+
+ def matches?(instance)
+ @instance = instance
+ @instance.valid?
+ @default_value.nil? ? value : value == @default_value
@gabebw
thoughtbot, inc. member
gabebw added a note Apr 13, 2012

I'm worried that this doesn't check for when people have a default value of false (e.g. boolean columns) but don't set an explicit @default_value. In those cases, value would be false, making this fail incorrectly.

What about this instead?

if @default_value.nil?  # test is just checking for any default value
  # Assume that people don't set NULL as a default value.  
  value != nil
else
  # Otherwise, check that the actual value and the expected value are the same.
  value == @default_value
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@mike-burns mike-burns commented on the diff May 17, 2012
spec/shoulda/active_model/have_a_default_matcher_spec.rb
@@ -0,0 +1,66 @@
+require 'spec_helper'
+
+describe Shoulda::Matchers::ActiveModel::HaveADefaultMatcher do
+
+ context "an attribute with a default value" do
+ before do
+ define_model :example, :attr => :string do
+ before_validation :set_attr
+ def set_attr
+ self.attr = "abc" if attr.nil?
+ end
@mike-burns
thoughtbot, inc. member
mike-burns added a note May 17, 2012

This is not the proper way to set a default value; instead you should set the default in the DB schema. Does this matcher work with that methodology?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@mike-burns
thoughtbot, inc. member

Hi @dlupu , any thoughts on the questions @gabebw and I raised?

Thanks,
-Mike

@mike-burns mike-burns closed this Jul 9, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.