Simple Rspec test for positive number just won't pass
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开发者_StackOverflow中文版] = -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:
order = Order.new(:order_size => -23)
order.should_not be_valid
why do you call create!
just call new
Or change your test to expect the creation to fail.
There are a few ways to write this test. You are using the create!
method, which will raise an exception when it fails. So in that case you would write your test as follows:
it "should require a positive order size" do
@attr[:order_size] = -23
expect { @user.orders.create!(@attr)}.to raise_error(ActiveRecord::RecordInvalid.new)
end
But, actually, the fact that the create!
does raise an exception when an order
is not valid, is rails-specific, so i would actually test it as proposed by @mharper.
精彩评论