Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing the Controller with RSpec, Devise, Factory Girl

I have models: Post and User(Devise). I am testing controller Post.

describe "If user sign_in" do

   before(:all){ 
     @user = Factory(:user)
   }

   it "should get new" do
     sign_in @user  
     get 'new'
     response.should be_success
     response.should render_template('posts/new')
   end

   it "should create post" do
     sign_in @user
     post 'create', :post => Factory(:post)
     response.should redirect_to(post_path(:post))
   end
 end  

But the second test fails:

Failure/Error: post 'create', :post => Factory(:post) ActiveRecord::RecordInvalid: Validation failed: Email has already been taken, Email has already been taken, Username has already been taken

How do I fix this?

like image 608
Mike Avatar asked Feb 12 '12 12:02

Mike


2 Answers

You don't need another gem for this. FactoryGirl has built in dynamic helpers for this. I suggest watching the short Railscast about this. Here is a snippet of how it works:

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "foo#{n}" }
    password "foobar"
    email { "#{username}@example.com" }
like image 141
coneybeare Avatar answered Oct 07 '22 00:10

coneybeare


You need a tool to clean your database between tests. Because you should be able to run each test with a clean database. I'm using database_cleaner, it's quite a famous gem and it works really well. It's easy to setup too. An example from the README ( RSpec related):

RSpec.configure do |config|

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end
like image 24
lucapette Avatar answered Oct 07 '22 00:10

lucapette