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 forlet!
andscenario
is just an alias forit
. These are defined by Capybara.In RSpec,
let!
usebefore
under the hood. Eachbefore
block is run in order of definition. This means that, if you define abefore(:each)
block before alet!
block, you're telling RSpec to run thelet!
block after thebefore(:each)
block. In this case, you're creating a design after visiting the designs path.All
before
blocks after evaluated beforeit
blocks. This is why you were able to see the record in the database in yourbinding.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
) intoscenario
blocks, as usingbefore
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.