Reputation: 4797
I have a very simple test on a Deal model that keeps failing and I can't understand why.
My Deal model:
class Deal < ActiveRecord::Base
belongs_to :admin_user, :foreign_key => 'admin_user_id'
attr_accessible :url_path,
:country,
:title,
:description,
:twitter_msg,
:image_url,
:prelaunch_date,
:deal_launch_date,
:deal_end_date,
:featured,
:admin_user_id
:as => :admin_user
validates :title,
presence: true,
length: { maximum: 200 }
The test:
require 'spec_helper'
describe Deal do
let(:admin_user) { FactoryGirl.create(:admin_user) }
before(:each) do
@attr = {
url_path: "lorem ipsum",
country: "France",
title: "lorem ipsum",
description: "lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum",
twitter_msg: "lorem ipsum",
image_url: "lorem ipsum",
prelaunch_date: 1.days.from_now.change(hour: 10),
deal_launch_date: 3.days.from_now.change(hour: 10),
deal_end_date: 15.days.from_now.change(hour: 10),
featured: true,
admin_user_id: 1
}
end
describe "tests on deal models validations for TITLES" do
it { should validate_presence_of(:title) }
it { should_not allow_value(" ").for(:title) }
it "should reject deals with title that is too long" do
long = "a" * 201
hash = @attr.merge(:title => long)
Deal.new(hash).should have(1).error_on(:title)
end
end
and the test fail with "Deal tests on deal's models validations for TITLES should reject deals with title that is too long Failure/Error: Deal.new(hash).should have(1).error_on(:title) expected 1 error on :title, got 2 => i don't get why i have 2 errors. i should get only one and my test would be passing!
The strangest thing:
- when I do rspec spec
it fails
- then if I change in my validates the number of characters to 195 and in my test to 196, it then passes
- but then, the next time I relaunch guard or my server, then it fails again
and if I change again to 190 and 191, it then works again, but as soon as I restart guard or my server
I tried this many times and it's always the same problem. I don't understand, it seems guard or my server is the problem.
Does anybody have a clue to why it happens and how I can correct this?
Upvotes: 2
Views: 3254
Reputation: 2357
With Shoulda Matchers gem installed, you can do a:
it { should validate_length_of(:title).is_at_most(200) }
Upvotes: 2
Reputation: 1929
You could use the shoulda matcher to test validations:
it { should ensure_length_of(:title).is_at_most(200) }
Upvotes: 4