I'm trying to clean my db between specs. So I decided to use the popular gem database_cleaner. The problem now is that when I create a new instance of a model with FactoryGirl, it is created but not showed in the page.
Here is my spec_helper:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
require 'factory_girl_rails'
require 'pry'
require 'database_cleaner'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.include FactoryGirl::Syntax::Methods
config.order = :random
Kernel.srand config.seed
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each, type: :feature) { DatabaseCleaner.strategy = :truncation }
config.before { DatabaseCleaner.start }
config.after { DatabaseCleaner.clean }
end
And the simple test I'm trying to run is this one:
require 'spec_helper'
feature 'designs' do
feature 'editing designs' do
before(:each) { visit designs_path}
given!(:design){ create(:design)}
scenario "from the designs index" do
binding.pry
expect(page).to have_content("Ninja Crane")
end
end
end
I use binding.pry to check the number of designs and see the page. The result is that the design is being created correctly but is not being showed in the page.
Thanks in advance!
It's worth noting that given!
is just an alias for let!
and scenario
is just an alias for it
. These are defined by Capybara.
In RSpec, let!
use before
under the hood. Each before
block is run in order of definition. This means that, if you define a before(:each)
block before a let!
block, you're telling RSpec to run the let!
block after the before(:each)
block. In this case, you're creating a design after visiting the designs path.
All before
blocks after evaluated before it
blocks. This is why you were able to see the record in the database in your binding.pry
statement.
I'd recommend putting all of your given!
definitions at the top, to make sure they are defined before evaluating any of your specs.
I'd also moving the exercise phase of the test (visit design_path
) into scenario
blocks, as using before
makes it harder to tell what you're actually testing and makes it more likely that the test runs in a different order than you're expecting.