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?
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):