FactoryGirl and Rspec

I am very green for this TDD business, so any help would be fantastic!

So I have a factory with the following:

FactoryGirl.define do factory :account do email "example@example.com" url "teststore" end end 

And the Rspec test with:

  it "fails validation without unique email" do account1 = FactoryGirl.create(:account) account2 = FactoryGirl.create(:account) account2.should have(1).error_on(:email) end 

I get an error with the following message:

  1) Account fails validation without unique email Failure/Error: account2 = FactoryGirl.create(:account) ActiveRecord::RecordInvalid: Validation failed: Email taken, please choose another, Url taken, please choose another # ./spec/models/account_spec.rb:11:in `block (2 levels) in <top (required)>' 

Is this the right way to create new plants? Any ideas what I'm doing wrong here (I have no doubt that I'm doing something completely wrong!)

EDIT: I think, instead of using "create" in the second account, I can use .build and use ss instead?

+8
ruby-on-rails tdd ruby-on-rails-3 rspec factory-bot
source share
2 answers

Keep interacting with databases and use the build method for such situations.

 it "fails validation without unique email" do account1 = create(:account) account2 = build(:account) account2.should_not be_valid account2.should have(1).error_on(:email) end 

You do not need to try to create an account for valid? to return false. You have access to the error object in your account, even when it is simply embedded in memory. This will reduce database interaction and thus make your tests much faster.

Have you considered using sequences in your factories? I don't know how far your RSpec / FactoryGirl experience goes, but you will find that things like the following are very useful.

factories.rb

 factory :account do sequence(:email) { |n| "user#{n}@example.com" } url "teststore" end 

Each time you invoke build or create in the factory account, you will receive unique emails.

Remember that you can always specify values ​​for attributes in a factory using hash parameters. Therefore, by checking your uniqueness check in your account, you would do something like this.

 it "fails validation without unique email" do account1 = create(:account, :email => "foo@bar.com") account2 = build(:account, :email => "foo@bar.com") account2.should_not be_valid account2.should have(1).error_on(:email) end 
+15
source share

Try the following:

 FactoryGirl.create(:account) lambda { FactoryGirl.create(:account) }.should raise_error(ActiveRecord::RecordInvalid) 

This will help - with similar syntax in what you do.

However, searching for β€œrspec validate_uniqueness_of” will find you some more elegant approaches instead of using factory girl like this!

0
source share

All Articles