Cannot rerun my app with guard or rerun - ruby

So I have an app, the tree is something like this:
- Gemfile
- Guardfile
- source/
- dist/
- app.rb
The command to start the server is ruby app.rb ( or require_relative './app.rb', which does the same thing)
I want to run this command and re run it whenever any file changes.
The only exception is the dist/ folder - any file changes in there should be ignored.
Here's my attempt so far with guard and guard-shell (apologies for the code dump):
require 'childprocess'
# Global constant tracking whether the app has been started
RunningProcess = {gen_rb: false}
# Method to stop the app if it's been started
def ensure_exited_server
begin
RunningProcess[:gen_rb] && RunningProcess[:gen_rb].poll_for_exit(10)
rescue ChildProcess::TimeoutError
RunningProcess[:gen_rb].stop # tries increasingly harsher methods to kill the process.
end
nil
end
# Start the app using 'child-process'
def start_app
# prevent 'port in use' errors
ensure_exited_server
# The child-process gem starts a process and exposes its stdout
RunningProcess[:gen_rb] = ChildProcess.build("ruby", "gen.rb")
RunningProcess[:gen_rb].io.inherit!
RunningProcess[:gen_rb].start
nil
end
# Always start the app, not just when a file changes.
start_app
# The guard-shell gem runs a block whenever some set of files has changed.
guard :shell do
# This regex matches anything except the dist/ folder
watch /^[^dist\/].+/ do |m|
start_app
# Print a little message when a file changes.
m[0] + " has changed."
end
nil
end
# Make sure the app does not run after guard exits
at_exit { ensure_exited_server }
This doesn't ever restart my app.
The problem with rerun is something I raised an issue on their repo about: see https://github.com/alexch/rerun/issues/107

How about something like this for your Guardfile?
guard :shell do
watch(%r{^source/.+\.(rb)}) do |m|
`ruby app.rb`
end
watch('app.rb') do |m|
`ruby app.rb`
end
end
Instead of listing which directories to ignore, this watch states which directories/files to use.

Related

Aruba: Command "seedly-calculator" not found in PATH-variable

So, I am trying to run the test but I am getting an error says.
Aruba::LaunchError:Command "seedly-calculator.rb" not found in PATH-variable
-seedly-calculator
-bin
-src
-seedly-calculator.rb
I have tried to change the path in rake file but it doesn't work.
My seedly-calculator.rb file is in the root directory.
require "rspec/core/rake_task"
namespace :spec do
desc "Run the functional suite against the CLI"
RSpec::Core::RakeTask.new(:functional, [] => [:set_path])
task :set_path do
project_bin_dir = File.join(File.dirname(File.expand_path(__FILE__)), '..', 'bin')
ENV['PATH'] = project_bin_dir + ':'+ ENV['PATH']
end
end
it shows error like:
Failure/Error: let(:command) { run "seedly-calculator.rb" }
Aruba::LaunchError:
Command "seedly-calculator.rb" not found in PATH-variable "/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/bin:/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/exe:/Users/bilaltariq/.rbenv/versions/2.6.2/lib/ruby/gems/2.6.0/bin:/Users/bilaltariq/Desktop/seedly-calculator/functional_spec/../bin:/Users/bilaltariq/.rbenv/versions/2.6.2/bin:/usr/local/Cellar/rbenv/1.1.1/libexec:/Users/bilaltariq/.rbenv/shims:/Users/bilaltariq/.asdf/shims:/Users/bilaltariq/.asdf/bin:/usr/local/bin:/Users/bilaltariq/.bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin".
I expect it to hit the file so i can write some test.
am i doing something wrong?
require 'spec_helper'
RSpec.describe 'Command Validation', type: :aruba do
let(:command) { run "seedly-calculator.rb" }
it "wrong/missing arguments" do
command.write("lookup\n")
stop_all_commands
expect(command.output).to end_with("Missing bank_name argument.\n")
end
end
seedly-calculator.rb:
#!/usr/bin/env ruby
# Complete bin/setup so that after it is
# run, ruby seedly-calculator.rb can be used to launch
# it.
# frozen_string_literal: true
require_relative './src/runner'
if !ARGV.length.zero?
input = ARGV
Runner.new.send('process_input', input)
else
puts "Arguments required!."
end
Update
To run a ruby script using run you need to make sure your ruby script is executable and contains a shebang so your system knows to run it with ruby. Here's example from this starter example
#!/usr/bin/env ruby
file = ARGV[0]
if file.nil? || file.empty?
abort "aruba-test-cli [file]: Filename is missing"
elsif !File.exist? file
abort "aruba-test-cli [file]: File does not exist"
end
puts File.read(file).chomp
So in your case you'll need to add this to the first line of your seedly-calculator.rb file
#!/usr/bin/env ruby
Then run this from command line to make it executable.
chmod +x #!/usr/bin/env ruby
I made a simple example forked off the one I reffed above. See this commit
Rspec convention is that it should match the same file structure of your project. It is not a good idea to set PATH manually.
Rake tasks are normally put in a tasks folder so you should have in project root a tasks folder
my_project/tasks/something.rake
Then you should have a spec folder that matches
my_project/spec/tasks/something_spec.rb
Then you should be able to get rid of task :set_path do end block and just run the spec without that.
You should also have a Gemfile to load your gems, run bundle install then invoke your test with
bundle exec rspec spec/tasks/sometask_spec.rb

Could not find 'rspec/autorun'

I'm trying to do the first example of The rspec book
greeter_spec.rb
class RSpecGreeter
def greet
"Hello RSpec!"
end
end
describe "RSpec Greeter" do
it "should say 'Hello RSpec!' when it receives the greet() message" do
greeter = RSpecGreeter.new
greeting = greeter.greet
greeting.should == "Hello RSpec!"
end
end
When I run $ rspec greeter_spec.rb the output should be something like this:
.
Finished in 0.00075 seconds
1 example, 0 failures
but I got:
Could not find 'rspec/autorun'
This may happen if you're using rubygems as your package manager, but it is not
being required through some mechanism before executing the rspec command.
You may need to do one of the following in your shell:
# for bash/zsh
export RUBYOPT=rubygems
# for csh, etc.
set RUBYOPT=rubygems
For background, please see http://gist.github.com/54177.
I tried to include require 'rspec/autorun' at the top of the file but doesn't work, also I did what they suggest on the output but still not working.
I'm using ruby version 2.0.0p648, and rspec 2.0.0

Ruby Guard ignore files

I would like to run the requirejs optimization script when any .js file is changed (except for built.js).
I read there is an ignore method. I have the following in my Gaurdfile (which is causing an infinite loop).
guard 'shell', :ignore => 'built.js' do
watch(/script\/(.*).js/) { `node r.js -o build.js` }
end
My question is: How do I configure my Guardfile to ignore the file built.js?
First, assuming you already have the guard-shell gem installed...
I think this gives you something to work from given what you are trying to do.
It will ignore the script/build.js file and trigger a shell command when any other .js file changes.
ignore /script\/build.js/
guard :shell do
watch /.*\.js/ do |m|
`yourcommandhere`
msg = "Processed #{m[0]}"
n msg, 'mycustomshellcommand'
"-> #{msg}"
end
end
See this link for Guardfile examples.
See this link for the syntax of guard-shell.

RSpec: kernel_require.rb:45:in `require': cannot load such file -- bowling.rb (LoadError)

Following the example here:
http://rspec.info
however it fails with:
kernel_require.rb:45:in `require': cannot load such file -- bowling.rb (LoadError)
even though I've got a bowling.rb file.
Any suggestions?
UPDATE
Project listing:
ls -l
-rw-r--r-- 1 snowcrash snowcrash 77 10 Jul 19:43 bowling.rb
-rw-r--r-- 1 snowcrash snowcrash 205 10 Jul 19:49 bowling_spec.rb
$ rspec bowling_spec.rb
/Users/snowcrash/.rvm/rubies/ruby-2.0.0-p195/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require': cannot load such file -- bowling (LoadError)
and code listings:
Spec:
# bowling_spec.rb
require 'bowling'
describe Bowling, "#score" do
it "returns 0 for all gutter game" do
bowling = Bowling.new
20.times { bowling.hit(0) }
bowling.score.should eq(0)
end
end
Class file:
# bowling.rb
class Bowling
def hit(pins)
end
def score
0
end
end
The rspec home page unfortunately does not tell you about initializing rspec in your project.
Assuming you have a project folder called 'bowling', inside the bowling folder run
rspec --init
This will create the spec directory and two files
spec/spec_helper.rb
.rspec
The .rspec file lets you define preferences like color and format
--color
--format documentation
Now in spec_helper.rb, add require "bowling"
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
require "bowling"
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
end
Now inside your bowling_spec.rb, add `require "spec_helper"
require "spec_helper"
class Bowling
def hit(pins)
end
def score
0
end
end
Also, any other specs you add you need to add require "spec_helper". The comments in spec_helper.rb explain why this is necessary.
Here is a good beginner explanation of setting up and working with rspec
Good luck
I'm a complete noob in ruby (coming from java) and had a similar problem to get rspec running.
The above answer helped to point the right way but did not work for me at first.
After reading the provided link i got it running with the following solution:
first run rspec --init.
then i edited the spec_helper.rb file with require_relative '../bowling'.
looked like this:
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
require_relative '../bowling'
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
The other two files looked like this:
bowling_spec.rb:
# bowling_spec.rb
describe Bowling, "#score" do
it "returns 0 for all gutter game" do
bowling = Bowling.new
20.times { bowling.hit(0) }
bowling.score.should eq(0)
end
end
and bowling.rb:
# bowling.rb
class Bowling
def hit(pins)
end
def score
-1
end
end
That was enough. I found it strange that there is no hint in the docs to run rspec --init first to get it running.
Maybe something is wrong with my installation (rbenv ) so that i have to use require_relative ?

ruby rake guard task

Ruby noob - I need to have guard running in my rake tasks but I can't find a way to have it run in the background. It needs to run 2nd last, therefore having the guard > shell waiting for commands is preventing the final task from running, so calling sh bundle exec guard in the rake file is not an option. According to the documentation this should work:
##
desc "Watch files"
##
task :watcher do
Guard.setup
Guard::Dsl.evaluate_guardfile(:guardfile => 'Guardfile', :group => ['Frontend'])
Guard.guards('copy').run_all
end
#end watch files
https://github.com/guard/guard/wiki/Use-Guard-programmatically-cookbook
Here is my Guardfile, in full, (in same dir as Rakefile)
# Any files created or modified in the 'source' directory
# will be copied to the 'target' directory. Update the
# guard as appropriate for your needs.
guard :copy, :from => 'src', :to => 'dist',
:mkpath => true, :verbose => true
But rake watcher returns an error:
07:02:31 - INFO - Using Guardfile at Guardfile.
07:02:31 - ERROR - Guard::Copy - cannot copy, no valid :to directories
rake aborted!
uncaught throw :task_has_failed
I have tried different hacks, too many to mention here, but all have returned the above Guard::copy - cannot copy, no valid :to directories. The dist directory definitely exists. Also if I call guard from the shell, inside rake or on cmd line, then it runs perfect, but leaves me with the guard > shell. Think my issue maybe a syntax error in the rake file? any help appreciated ;)
Guard Copy does some initialization in the #start method, so you need to start the Guard before you can run it:
task :watcher do
Guard.setup
copy = Guard.guards('copy')
copy.start
copy.run_all
end
In addition there's no need to call Guard::Dsl.evaluate_guardfile anymore, that info on the wiki is outdated.
Edit 1: Keep watching
When you want to watch the dir, then you need to start Guard:
task :watcher do
Guard.start
copy = Guard.guards('copy')
copy.start
copy.run_all
end
Note: If you setup Guard and start it afterwards, then Guard fails with Hook with name 'load_guard_rc'
Edit 2: Really keep watching
Guard starts Listen in non blocking mode, so in order to make the call blocking, you need to wait for it:
task :watcher do
Guard.start
copy = Guard.guards('copy')
copy.start
copy.run_all
while ::Guard.running do
sleep 0.5
end
end
If you also want to disable interactions, you can pass the no_interactions option:
Guard.start({ no_interactions: true })
The API is absolutely not optimal and I'll improve it for Guard 2 when we remove Ruby 1.8.7 support and some deprecated stuff.

Resources