Ok say I have the following model:
class Country < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :code
end
I'm doing the rspec unit tests for those validations. They look like this:
it "should be invalid without a name" do
country = Country.new(#valid_attributes.except(:name))
country.should_not be_valid
country.errors.on(:name).should == "can't be blank"
country.name = #valid_attributes[:name]
country.should be_valid
end
it "should be invalid without a code" do
country = Country.new(#valid_attributes.except(:code))
country.should_not be_valid
country.errors.on(:code).should == "can't be blank"
country.code = #valid_attributes[:code]
country.should be_valid
end
This doesn't look quite DRY. Is there any gem or plugin that automates this kind of stuff?
I'd like to get something along these lines:
it "should be invalid without a name" do
test_presence_validation :name
end
it "should be invalid without a code" do
test_presence_validation :code
end
There are remarkable for that : http://github.com/carlosbrando/remarkable
After you can do
it { should validate_presence_of :name }
If you're using factory_girl, you can do:
it "should be invalid without a name" do
FactoryGirl.build(:country, name: nil).should_not be_valid
end
One suggestion... don't use the keyword "should" on every spec.
Instead, write: "is invalid without a name"
Try also accept_values_for gem.
It allows to do something like this:
describe User do
subject { User.new(#valid_attributes)}
it { should accept_values_for(:email, "john#example.com", "lambda#gusiev.com") }
it { should_not accept_values_for(:email, "invalid", nil, "a#b", "john#.com") }
end
Related
Here is my Spec file:
require 'spec_helper'
describe User, "references" do
it { should have_and_belong_to_many(:roles) }
it { should belong_to(:account_type) }
it { should belong_to(:primary_sport).class_name("Sport") }
it { should belong_to(:school) }
it { should belong_to(:city) }
end
describe User, "factory" do
before(:each) do
#user = FactoryGirl.create(:user)
end
it "is invalid with no email" do
#user.email = nil
#user.should_not be_valid
end
it "is valid with email" do
#user.should be_valid
end
end
Factory:
FactoryGirl.define do
factory :user do
email Faker::Internet.email
password "password"
password_confirmation "password"
agreed_to_age_requirements true
end
end
The part I am trying to "test" for and not sure how to 100% is checking to make sure when a User is created that the email address is not nil.
shoulda provides validation helpers to help you test the validations.
it { should validate_presence_of(:email) }
If you want to use rspec and write your own, then
describe User do
it "should be invalid without email" do
user = FactoryGirl.build(:user, :email => nil)
#user.should_not be_valid
#user.errors.on(:email).should == 'can't be blank' #not sure about the exact message. But you will know when you run the test
end
it "should be valid with email" do
user = FactoryGirl.build(:user, :email => "user#user.com")
#user.should be_valid
end
end
When you run the test, it would read as
User
should be invalid without email
should be valid with email
Giving a good description for your test case is very important, because it kind of acts like a documentation.
I try to set a instance variable in a subject before testing validity of model fields. I need to set this variable, because validation is conditional (it is used only for some type of users). So I have something like this:
context "as a user" do
before(:each) do
subject = Organization.new
subject.editor = "user"
end
it { subject.should validate_presence_of :name }
end
But it doesn't work as expected:
Failure/Error: it { subject.should validate_presence_of :description }
RuntimeError:
Organization#editor attr is not set
What did i miss?
subject in your before block is a local variable. It looks like you meant to use an explicit subject:
context "as a user" do
subject { Organization.new }
before(:each) do
subject.editor = "user"
end
# usually, you don't explicitly name the subject in an `it` like this
it { should validate_presence_of :name }
end
I have started my journey with TDD in Rails and have run into a small issue regarding tests for model validations that I can't seem to find a solution to. Let's say I have a User model,
class User < ActiveRecord::Base
validates :username, :presence => true
end
and a simple test
it "should require a username" do
User.new(:username => "").should_not be_valid
end
This correctly tests the presence validation, but what if I want to be more specific? For example, testing full_messages on the errors object..
it "should require a username" do
user = User.create(:username => "")
user.errors[:username].should ~= /can't be blank/
end
My concern about the initial attempt (using should_not be_valid) is that RSpec won't produce a descriptive error message. It simply says "expected valid? to return false, got true." However, the second test example has a minor drawback: it uses the create method instead of the new method in order to get at the errors object.
I would like my tests to be more specific about what they're testing, but at the same time not have to touch a database.
Anyone have any input?
CONGRATULATIONS on you endeavor into TDD with ROR I promise once you get going you will not look back.
The simplest quick and dirty solution will be to generate a new valid model before each of your tests like this:
before(:each) do
#user = User.new
#user.username = "a valid username"
end
BUT what I suggest is you set up factories for all your models that will generate a valid model for you automatically and then you can muddle with individual attributes and see if your validation. I like to use FactoryGirl for this:
Basically once you get set up your test would look something like this:
it "should have valid factory" do
FactoryGirl.build(:user).should be_valid
end
it "should require a username" do
FactoryGirl.build(:user, :username => "").should_not be_valid
end
Here is a good railscast that explains it all better than me:
UPDATE: As of version 3.0 the syntax for factory girl has changed. I have amended my sample code to reflect this.
An easier way to test model validations (and a lot more of active-record) is to use a gem like shoulda or remarkable.
They will allow to the test as follows:
describe User
it { should validate_presence_of :name }
end
Try this:
it "should require a username" do
user = User.create(:username => "")
user.valid?
user.errors.should have_key(:username)
end
in new version rspec, you should use expect instead should, otherwise you'll get warning:
it "should have valid factory" do
expect(FactoryGirl.build(:user)).to be_valid
end
it "should require a username" do
expect(FactoryGirl.build(:user, :username => "")).not_to be_valid
end
I have traditionally handled error content specs in feature or request specs. So, for instance, I have a similar spec which I'll condense below:
Feature Spec Example
before(:each) { visit_order_path }
scenario 'with invalid (empty) description' , :js => :true do
add_empty_task #this line is defined in my spec_helper
expect(page).to have_content("can't be blank")
So then, I have my model spec testing whether something is valid, but then my feature spec which tests the exact output of the error message. FYI, these feature specs require Capybara which can be found here.
Like #nathanvda said, I would take advantage of Thoughtbot's Shoulda Matchers gem. With that rocking, you can write your test in the following manner as to test for presence, as well as any custom error message.
RSpec.describe User do
describe 'User validations' do
let(:message) { "I pitty da foo who dont enter a name" }
it 'validates presence and message' do
is_expected.to validate_presence_of(:name).
with_message message
end
# shorthand syntax:
it { is_expected.to validate_presence_of(:name).with_message message }
end
end
A little late to the party here, but if you don't want to add shoulda matchers, this should work with rspec-rails and factorybot:
# ./spec/factories/user.rb
FactoryBot.define do
factory :user do
sequence(:username) { |n| "user_#{n}" }
end
end
# ./spec/models/user_spec.rb
describe User, type: :model do
context 'without a username' do
let(:user) { create :user, username: nil }
it "should NOT be valid with a username error" do
expect(user).not_to be_valid
expect(user.errors).to have_key(:username)
end
end
end
Given I have the following class
class listing > ActiveRecord::Base
attr_accessible :address
belongs_to :owner
validates :owner_id, presence: true
validates :address, presence: true
end
Is there a way I can get away with not having to keep associating an owner before I save a listing in my tests in /spec/models/listing_spec.rb, without making owner_id accessible through mass assignment?
describe Listing do
before(:each) do
#owner = Factory :owner
#valid_attr = {
address: 'An address',
}
end
it "should create a new instance given valid attributes" do
listing = Listing.new #valid_attr
listing.owner = #owner
listing.save!
end
it "should require an address" do
listing = Listing.new #valid_attr.merge(:address => "")
listing.owner = #owner
listing.should_not be_valid
end
end
No need to use factory-girl (unless you want to...):
let(:valid_attributes) { address: 'An Address', owner_id: 5}
it "creates a new instance with valid attributes" do
listing = Listing.new(valid_attributes)
listing.should be_valid
end
it "requires an address" do
listing = Listing.new(valid_attributes.except(:address))
listing.should_not be_valid
listing.errors(:address).should include("must be present")
end
it "requires an owner_id" do
listing = Listing.new(valid_attributes.except(:owner_id))
listing.should_not be_valid
listing.errors(:owner_id).should include("must be present")
end
There is if you use factory-girl
# it's probably not a good idea to use FG in the first one
it "should create a new instance given valid attributes" do
listing = Listing.new #valid_attr
listing.owner = #owner
listing.property_type = Factory(:property_type)
listing.save!
end
it "should require an address" do
# But here you can use it fine
listing = Factory.build :listing, address: ''
listing.should_not be_valid
end
it "should require a reasonable short address" do
listing = Factory.build :listing, address: 'a'*245
listing.should_not be_valid
end
I hate to be the voice of dissent here, but you shouldn't be calling save! or valid? at all in your validation spec. And 9 times out of 10, if you need to use factory girl just to check the validity of your model, something is very wrong. What you should be doing is checking for errors on each of the attributes.
A better way to write the above would be:
describe Listing do
describe "when first created" do
it { should have(1).error_on(:address) }
it { should have(1).error_on(:owner_id) }
end
end
Also, chances are you don't want to be checking for the presence of an address, you want to check that it is not nil, not an empty string, and that it is not longer than a certain length. You'll want to use validates_length_of for that.
i'm into rspec these days, trying to make my models more precise and accurate. Some things are still a bit weird to me about rspec and so i thought it would be nice if someone could clarify.
Let's say that i have a User model. This one has a :name. The name should be between 4..15 characters(that's a secondary objective, at first it must just exist). So now i'm thinking: What is the best way to test that in a manner that assures that this will happen. To test that a user must have a name, i wrote something like this :
describe User do
let(:user) { User.new(:name => 'lele') }
it "is not valid without a name" do
user.name.should == 'lele'
end
end
Now, i'm not quite sure that this accomplishes exactly what i want. It seems to me that i'm actually testing Rails with this one. Moreover, if i want to check that a name cannot be more than 15 chars and less than 4, how can this be integrated ?
EDIT:
Maybe this is better ?
describe User do
let(:user) { User.new(:name => 'lele') }
it "is not valid without a name" do
user.name.should_not be_empty
end
end
You're probably looking for the be_valid matcher:
describe User do
let(:user) { User.new(:name => 'lele') }
it "is valid with a name" do
user.should be_valid
end
it "is not valid without a name" do
user.name = nil
user.should_not be_valid
end
end
I use this way:
describe User do
it "should have name" do
lambda{User.create! :name => nil}.should raise_error
end
it "is not valid when the name is longer than 15 characters" do
lambda{User.create! :name => "im a very looooooooong name"}.should raise_error
end
it "is not valid when the name is shorter than 4 characters" do
lambda{User.create! :name => "Tom"}.should raise_error
end
end
I like to test the actual error messages for validations:
require 'spec_helper'
describe User do
let (:user) { User.new }
it "is invalid without a name" do
user.valid?
user.errors[:name].should include("can't be blank")
end
it "is invalid when less than 4 characters" do
user.name = "Foo"
user.valid?
user.errors[:name].should include("is too short (minimum is 4 characters)")
end
it "is invalid when greater than 15 characters" do
user.name = "A very, very, very long name"
user.valid?
user.errors[:name].should include("is too long (maximum is 15 characters)")
end
end
It's also helpful to use a factory that builds an object with valid attributes, which you can invalidate one at a time for testing.
I would use something similar to this
class User < ActiveRecord::Base
validates_presence_of :name
validates_length_of :name, :in => 4..15
end
describe User do
it "validates presence of name" do
user = User.new
user.valid?.should be_false
user.name = "valid name"
user.valid?.should be_true
end
it "validates length of name in 4..15" do
user = User.new
user.name = "123"
user.valid?.should be_false
user.name = "1234567890123456"
user.valid?.should be_false
user.name = "valid name"
user.valid?.should be_true
end
end
Most notable is that I'm using active record validations for both conditions. In my examples I don't rely on the error strings. In examples that test the behavior of validations there's no reason to touch the database so I don't. In each example I test the behavior of the object when it's both valid and invalid.