I am having trouble in cleaning database between features. I tried using Before hooks but it runs for each scenario but I only need to clean database at the start of each feature and not between scenarios.
Any suggestions would be helpful.
I am having trouble in cleaning database between features. I tried using Before hooks but it runs for each scenario but I only need to clean database at the start of each feature and not between scenarios.
Any suggestions would be helpful.
I use DatabaseCleaner https://github.com/DatabaseCleaner/database_cleaner I'm satisfed
config.before(:each) do |spec|
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
...
end
config.append_after(:each) do
DatabaseCleaner.clean
end
in rails_herper.rb
Here is sample config
before(:all) do
DatabaseCleaner.clean
end
In RSpec, you have tags, types, hooks etc..
In your case easiest way will be adding before(: all)
in each file.
This will start cleaning before all tests in described context.
From documentation Rspec Docs
before(:all) blocks are run once before all of the examples in a group
The database should be cleaned before every scenario as Cucumber intends. Stopping Cucumber from doing this is a false optimisation, and a common anti-pattern followed by lots of less experienced Cucumber users. Scenarios should never be dependent on each other.
To get this to work remove any code you have added to your application to restrict how cucumber cleans the database.
If you are not sure how to do this create a new rails project using the same ruby and rails versions you are using and then add the cucumber-rails gem. It will setup everything as intended. You can use the diff of before/after cucumber-rails to compare.
You can clean database before (not after) each scenario with the following code. Just add it to your features/support/env.rb
Cucumber::Rails::Database.autorun_database_cleaner = false
DatabaseCleaner.strategy = :truncation
Cucumber::Rails::Database.javascript_strategy = :truncation
Before do
DatabaseCleaner.clean
end
Just a work around/hack, just in case you haven't found a solution yet. The trick here is to use tagged cucumber hooks!
Provide a tag like @LastScenario in your last scenario in the feature file/s. Then using the @After hook of cucumber perform the action, say data clean up in your case. Something like: @LastScenario Scenario: My Scenario Name Given I have something...
And then in the Hooks.java Class:
public class Hooks {
@After("@LastScenario")
public void dataCleanUp() {
CleanUpScripts cleanUpScripts = new CleanUpScripts();
cleanUpScripts.dataCleanUp();
}
}
Same can be done using @Before Hook as well - based on what is required.