Sunday, September 18, 2011

Cucumber tests run twice in Rails 3 using an engine (fixed)

Recently, I had a problem with Cucumber tests running twice in a Rails 3 web app after I added a dependency on a Rails engine that I have extracted from another web app. After some investigation, I found out that given that the engine has its own Cucumber.rake, it ends up getting automatically included in the rake tasks of the web app when running "rake", thus queuing Cucumber tests to be run twice.

I solved the problem by adding the following in the Rails engine's Cucumber.rake file:

begin
  EngineModuleName::Application


  ... original Cucumber.rake content


  rescue NameError => e
end

Of course, for that to work, you need to make sure that you have defined an "application.rb" for the engine project with the correct engine module name namespace. That is usually done as part of setting up a new Rails engine project to allow invoking tests in the engine independently of any particular Rails project (by faking a Rails app in the engine).

Then, by adding the code above around Cucumber.rake's original content in the Rails engine project, you are saying that unless you are running within the scope of the engine's application, do not run the original content of Cucumber.rake. That gets rid of the problem of Cucumber tests running twice in any web app consuming the engine.

Happy Cucumber testing with Rails engine reuse!

No comments: