Search code examples
ruby-on-railsrspeccapybarafactory-botdatabase-cleaner

RSpec, Factory Girl and Capybara: no items saved


I have mountable Rails engine with RSpec:

RSpec.configure do |config|
  config.use_transactional_fixtures = false

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

  config.before(:each) do |example|
    DatabaseCleaner.strategy= example.metadata[:js] ? :truncation : :transaction
    DatabaseCleaner.start
  end

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

Simple factory:

FactoryGirl.define do
  factory :post, :class => MyEngine::Post do
    title 'title'
  end
end

Capybara feature:

require 'spec_helper'

describe 'Post', :type => :feature do
  let(:post) { FactoryGirl.create :post }

  it 'index action should have post' do
    visit posts_path
    expect(page).to have_text(post.title)
  end
end

And Post model doesn't have any validations.

But when i running tests it shows that there is no posts created.

Also ActiveRecord logs:

INSERT INTO "my_engine_posts" ...
RELEASE SAVEPOINT active_record_1
rollback transaction

Solution

  • This spec will always fail.

    let in RSpec is lazy loading. post is not actually created until you reference it in:

    expect(page).to have_text(post.title)
    

    So you can either use let! which is not lazy loading or reference post before you visit the page:

    require 'spec_helper'
    
    describe 'Post', :type => :feature do
      let(:post) { FactoryGirl.create :post }
    
      it 'index action should have post' do
        post
        visit posts_path
        expect(page).to have_text(post.title)
      end
    end