change cucumber runtime options - ruby

Is there any way to programmatically change options for the runtime object which is used for cucumber feature execution?
In Ruby + Cucumber: How to execute cucumber in code? it is described how to run tests from ruby script, but in addition to that I need to change some runtime options like profile, etc.
Looking at the source code a can see that there is a runtime.configure method, but I do not know which option to pass in to change anything.
Any help regarding this issue is much appreciated!

Create a Rake file like the one below and pass your options
require 'rubygems'
require 'cucumber'
require 'cucumber/rake/task'
Cucumber::Rake::Task.new :features do |t|
t.cucumber_opts = "*.feature -f json -o cucumber.json"
end

Related

Why does Watir-webdriver open two browsers?

I'm working on website test automation using Cucumber/Ruby/Selenium-Webdriver/Capybara. I want to switch to Watir-Webdriver in combination with Cucumber and Ruby, but I'm struggling with the following:
Every time I run my cucumber test, Watir opens two browser windows, a blank screen to the site I configurated as default, plus another in which the actual test steps are executed.
My 'Support/env.rb' file has:
require 'allure-cucumber'
require 'rspec'
require 'watir-webdriver'
AllureCucumber.configure do |c|
c.output_dir = 'D:\Test\result'
c.clean_dir = true
c.tms_prefix = '#PRACTEST--'
c.issue_prefix = '#JIRA++'
c.severity_prefix = '#URGENCY:'
c.tms_prefix = ''
end
My steps file begins with:
require 'watir-webdriver'
require 'cucumber'
require 'rspec'
require_relative 'D:\EntelTest\src\PageObject\home_page.rb'
Before do
#test = AbstractPage.new(Watir::Browser.new :ff)
#test.full_size
end
After do
#test.quit
end
home_page = nil
When(/^Go to home page$/) do
home_page = #test.goToHomePage
end
Can you put these before do and after do in hooks.rb? In the steps.rb file, just mention the code for your cucumber steps, and before that declare browser = Watir::Browser.new :ff
The best practice is to put it in hooks.rb. env.rb usually should consist the desired capabilities plus server environment codes. :)
What you have put in step file should go in hooks.rb file.
Please install gem called testnow.
It will help you to create most standard and easy to use watir-webdriver framework with all pre-configured browsers.
Steps:
1) gem install testnow
2) testnow watir_cucumber_now
It will as you to install dependecies, enter Y to set it up completely.
It will create robust framework with a sample scenario.
Just run the sample scenario with any of the following commands.
rake testnow BROWSER=firefox
rake testnow BROWSER=chrome
rake testnow BROWSER=opera
This will only work provided you have browsers pre-installed and webdriver present in PATH variable.
Please comment for more information.
Hope it helps!!

How to require file from `gem` which are not under `lib` directory?

I want to write spec for my rubocop custom cop. This gem has handy helpers defined here. I want to require it. How to achieve what?
I've tried to use Gem.find_files, and this gives me ability to require any file in that gem, but only under lib directory.
For example:
# this requires ...gems/rubocop-0.29.1/lib/rubocop/formatter/formatter_set.rb
require Gem.find_files('rubocop/formatter/formatter_set.rb').first
# but I need ...gems/rubocop-0.29.1/spec/support/cop_helper.rb
The following describes why I need it. I have spec/rubocop/my_custom_cop_spec.rb
require 'spec_helper'
require ? # What I should I write?
RSpec.describe RuboCop::Cop::Style::MyCustomCop do
it 'some test' do
inspect_source(cop, 'method(arg1, arg2)') # This helper I want to use from rubocop spec helpers
end
end
When I try plain require:
require 'rubocop/spec/support/cop_helper'
I receive error:
/home/user/.gem/ruby/2.0.0/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274
:in `require': cannot load such file -- rubocop/spec/support/cop_helper
I found a solution that I think is a little more syntactically elegant:
gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
I was so blinded, I already have path to file and able to get relative from it.
require 'pathname'
rubocop_path = Pathname.new(Gem.find_files('rubocop.rb').first).dirname
rubocop_path # => ...gems/rubocop-0.29.1/lib
require "#{rubocop_path}/../spec/support/cop_helper.rb"

Running rspec from within ruby multiple times within the same process

I am creating a test automation tool that runs a rspec test from within ruby, not from command line.
I run my test like this that runs and gives me a output hash with pass / fail etc.
config = RSpec.configuration
json_formatter = RSpec::Core::Formatters::JsonFormatter.new(config.out)
reporter = RSpec::Core::Reporter.new(json_formatter)
config.instance_variable_set(:#reporter, reporter)
RSpec::Core::Runner.run(["#{Rails.root}/spec/test1_spec.rb"])
puts json_formatter.output_hash
All is great until i run it again and i get the error
> undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_7:0x007ff3d343d978>
how do i reload / make sure all spec_helper and files are loaded before i run it again ?
thanks
Rick
Add
require 'spec_helper'
to the top of each spec file.
I had the same problems, turns out it can be fixed with one line of code only:
require 'capybara'
include Capybara::DSL # Add this line right after requiring capybara
Source: http://codedecoder.wordpress.com/2013/01/10/undefined-method-visit-for-rspec-capybara/
I had a similar issue and had to do a RSpec#reset between runs to make sure everything was cleaned up.
http://www.rubydoc.info/github/rspec/rspec-core/RSpec#reset-class_method

How to integrate rubocop with Rake?

rubocop is a code style checker for Ruby. A similar tool to rubocop, Cane, can be integrated with Rake. I prefer rubocop to Cane since rubocop makes checks based on the Ruby Style Guide and it seems to spot more problems. To automate the process of style checking I would like to integrate rubocop with Rake so that the build fails if code quality is lacking.
Gem already supports adding tests to packages via Rake. I would like to do the same with style checks so that style checks are run along with the tests. How can I do this?
If it helps to start with a Rakefile here is one:
# -*- coding: utf-8; mode: ruby -*-
require 'bundler/gem_tasks'
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/unit/test*.rb']
end
desc 'Run tests'
task default: :test
As of version 0.10.0 rubocop contain a custom rake task that you can use. Just put the following in your Rakefile
require 'rubocop/rake_task'
RuboCop::RakeTask.new
Make sure to use upper-case 'R' and 'C' or you will get a NameError.
I highly recommend,
require 'rubocop/rake_task'
RuboCop::RakeTask.new(:rubocop) do |t|
t.options = ['--display-cop-names']
end
This uses the rubocop's own rake tasks and allows you to pass options if you like.
You will probably find https://github.com/yujinakayama/guard-rubocop useful if you use Guard for your RSpec tests. It enables Rubocop to give you instant feedback as soon as you save the file, along with your test results.
I needed to do something similar myself, and ended up looking in the internal source code of the RuboCop::RakeTask here:
https://github.com/rubocop/rubocop/blob/a34a1c2c2dd1fa6d90ffd06c183421a495a0717c/lib/rubocop/rake_task.rb#L40-L43
require 'rubocop'
cli = CLI.new
puts 'Running RuboCop...' if verbose
result = cli.run(options)
abort('RuboCop failed!') if result.nonzero? && fail_on_error
You can actually invoke similar code directly in your own codebase / rake task.
I ended up writing a little wrapper module I can call to, with some default flags that I always want to be applied:
module RubocopCli
def self.run!(*args)
require "rubocop"
cli = RuboCop::CLI.new
result = cli.run(["--display-cop-names", "--force-exclusion", "--fail-level", "autocorrect", *args])
raise "RubocopCli.run! Linting failed." if result.nonzero?
end
end
Then you can call it with additional args from any task, or app code, like:
files_to_lint = %w[lib/whatever.rb spec/lib/whatever_spec.rb]
RubocopCli.run!("--auto-correct", *files_to_lint)
You can shell out via Rake with the options you prefer:
desc 'Run Rubocop with options'
task rubocop: :environment do
sh 'bundle exec rubocop -D --format offenses --format progress || true'
end
I then recommend modifying the default task to include the output. The trick is to clear the task and then add back what you want. Note the need to end with || true so that an error from Rubocop will not prevent the next task from running. Here's what I do, which also uses parallel tests:
task(:default).clear.enhance ['parallel:parallel_prepare', 'parallel:spec',
'parallel:features', 'lint:rubocop',
'lint:rails_best_practices']
I would recommend shelling out to the rubocop program. It's the simplest solution. Just add this to your Rakefile:
task test: :rubocop
task :rubocop do
sh 'rubocop'
end

Testing a rake task in rspec (and cucumber)

I'm new to Ruby, and I've been trying to learn Rake, RSpec, and Cucumber. I found some code that will help me test my Rake tasks, but I'm having trouble getting it to work. I was told here: http://blog.codahale.com/2007/12/20/rake-vs-rspec-fight/ to drop this:
def describe_rake_task(task_name, filename, &block)
require "rake"
describe "Rake task #{task_name}" do
attr_reader :task
before(:all) do
#rake = Rake::Application.new
Rake.application = #rake
load filename
#task = Rake::Task[task_name]
end
after(:all) do
Rake.application = nil
end
def invoke!
for action in task.instance_eval { #actions }
instance_eval(&action)
end
end
instance_eval(&block)
end
end
into my spec_helper.rb file.
I've managed to take this code out and run it in my cucumber steps like this:
When /^I run the update_installers task$/ do
#rake = Rake::Application.new
Rake.application = #rake
load "lib/tasks/rakefile.rb"
#task = Rake::Task["update_installers"]
for action in #task.instance_eval { #actions }
instance_eval(&action)
end
instance_eval(&block)
Rake.application = nil
end
but when I try to get things working in rspec, I get the following error.
ArgumentError in 'Rake task
install_grapevine should install to
the mygrapevine directory'
wrong number of arguments (1 for 2)
/spec/spec_helper.rb: 21:in instance_eval'
/spec/spec_helper.rb: 21:inblock in invoke!'
/spec/spec_helper.rb: 20:in each'
/spec/spec_helper.rb: 20:ininvoke!'
/spec/tasks/rakefile_spec.rb:12:in `block (2 levels) in
'
Unfortunately, I've got just under a week of ruby under by belt, so the metaprogramming stuff is over my head. Could anyone point me in the right direction?
This works for me: (Rails3/ Ruby 1.9.2)
When /^the system does it's automated tasks$/ do
require "rake"
#rake = Rake::Application.new
Rake.application = #rake
Rake.application.rake_require "tasks/cron"
Rake::Task.define_task(:environment)
#rake['cron'].invoke
end
Substitute your rake task name here and also note that your require may be "lib/tasks/cron" if you don't have the lib folder in your load path.
I agree that you should only do minimal work in the Rake task and push the rest to models for ease of testing. That being said I think it's important to ensure that the code is ACTUALLY run in my cron tasks during my integration tests so I think very mild testing of the rake tasks is justified.
Since testing rake is just too much for me, I tend to move this problem around. Whenever I find myself with a long rake task that I want to test, I create a module/class in lib/ and move all the code from the task there. This leaves the task to a single line of Ruby code, that delegates to something more testable (class, module, you name it). The only thing that remains untested is whether the rake task invokes the right line of code (and passes the right parameters), but I think that is OK.
It might be useful to tell us which is the 21nd line of your spec_helper.rb. But given that the approach you posted digs deep in rake (referring to its instance variables), I would entirely abandon it for what I suggested in the previous paragraph.
I've just spent a little while getting cucumber to run a rake task so I thought I'd share my approach. Note: This is using Ruby 2.0.0 and Rake 10.0.4, but I don't think the behaviour has changed since previous versions.
There are two parts to this. The first is easy: with a properly set up instance of Rake::Application then we can access tasks on it by calling #[] (eg rake['data:import']). Once we have a task we can run it by calling #invoke and passing in the arguments (eg rake['data:import'].invoke('path/to/my/file.csv').
The second part is more awkward: properly setting up an instance of Rake::Application to work with. Once we've done require 'rake' we have access to the Rake module. It already has an application instance, available from Rake.application, but it's not yet set up — it doesn't know about any of our rake tasks. It does, however, know where to find our Rakefile, assuming we've used one of the standard file names: rakefile, Rakefile, rakefile.rb or Rakefile.rb.
To load the rakefile we just need to call #load_rakefile on the application, but before we can do that we need to call #handle_options. The call to #handle_options populates options.rakelib with a default value. If options.rakelib is not set then the #load_rakefile method will blow up, as it expects options.rakelib to be enumerable.
Here's the helper I've ended up with:
module RakeHelper
def run_rake_task(task_name, *args)
rake_application[task_name].invoke(*args)
end
def rake_application
require 'rake'
#rake_application ||= Rake.application.tap do |app|
app.handle_options
app.load_rakefile
end
end
end
World(RakeHelper)
Pop that code into a file in features/support/ and then just use run_rake_task in your steps, eg:
When /^I import data from a CSV$/ do
run_rake_task 'data:import', 'path/to/my/file.csv'
end
The behavior might have changed since the correct answer was posted. I was experiencing problems executing two scenarios that needed to run the same rake task (only one was being executed despite me using .execute instead of .invoke). I thought to share my approach to solve the issue (Rails 4.2.5 and Ruby 2.3.0).
I tagged all the scenarios that require rake with #rake and I defined a hook to setup rake only once.
# hooks.rb
Before('#rake') do |scenario|
unless $rake
require 'rake'
Rake.application.rake_require "tasks/daily_digest"
# and require other tasks
Rake::Task.define_task(:environment)
$rake = Rake::Task
end
end
(Using a global variable is suggested here: https://github.com/cucumber/cucumber/wiki/Hooks#running-a-before-hook-only-once)
In the step definition I simply called $rake
# step definition
Then(/^the daily digest task is run$/) do
$rake['collector:daily_digest'].execute
end
Any feedback is welcome.

Resources