I’m new to rails and trying to write my first app. I have a table with columns order_size:integer and price:decimal(8,5). The price column holds currency prices so it needs to be really precise, in case you’re wondering. I’m trying to write tests to make sure the price and order_size are a positive numbers, but no matter what I do they won’t pass.
Here are the Rspec tests
it "should require a positive order size" do
@attr[:order_size] = -23
@user.orders.create!(@attr).should_not be_valid
end
it "should require a positive price" do
@attr[:price] = -1.2908
@user.orders.create!(@attr).should_not be_valid
end
Here are the Order class validations
validates_presence_of :user_id
validates_numericality_of :order_size, :greater_than => 0,
:only_integer => true
validates_numericality_of :price, :greater_than => 0
Here’s the test results
Failures:
1) Order validations should require a positive order size
Failure/Error: @user.orders.create!(@attr).should_not be_valid
ActiveRecord::RecordInvalid:
Validation failed: Order size must be greater than 0
# ./spec/models/order_spec.rb:39:in `block (3 levels) in <top (required)>'
2) Order validations should require a positive price
Failure/Error: @user.orders.create!(@attr).should_not be_valid
ActiveRecord::RecordInvalid:
Validation failed: Price must be greater than 0
# ./spec/models/order_spec.rb:44:in `block (3 levels) in <top (required)>'
What exactly is going on here? I even tried running the test asserting they should be_valid, but they still fail. Any help would be appreciated.
Looks to me like the creation of the records is failing due to your validations, and thus never getting to your assertion! As apneadiving points out, you want to do: