How to use RSpec without Rails? - ruby

What is the process for doing TDD in Ruby with RSpec without Rails?
Do I need a Gemfile? Does it only need rspec in it?
Ruby 1.9.3

The process is as follows:
Install the rspec gem from the console:
gem install rspec
Then create a folder (we'll name it root) with the following content:
root/my_model.rb
root/spec/my_model_spec.rb
#my_model.rb
class MyModel
def the_truth
true
end
end
#spec/my_model_spec.rb
require_relative '../my_model'
describe MyModel do
it "should be true" do
MyModel.new.the_truth.should be_true
end
end
Then in the console run
rspec spec/my_model_spec.rb
voila!

From within your projects directory...
gem install rspec
rspec --init
then write specs in the spec dir created and run them via
rspec 'path to spec' # or just rspec to run them all

The workflows around gem install rspec are flawed. Always use Bundler and Gemfile to ensure consistency and avoid situations where a project works correctly on one computer but fails on another.
Create your Gemfile:
source 'https://rubygems.org/'
gem 'rspec'
Then execute:
gem install bundler
bundle install
bundle exec rspec --init
The above will create .rspec and spec/spec_helpers.rb for you.
Now create your example spec in spec/example_spec.rb:
describe 'ExampleSpec' do
it 'is true' do
expect(true).to be true
end
end
And run the specs:
% bundle exec rspec
.
Finished in 0.00325 seconds (files took 0.09777 seconds to load)
1 example, 0 failures

Related

Ruby Gem: Uninitialized constant FactoryBot

Working on a Ruby gem and trying to use FactoryBot inside with RSpec.
I have this in support/factory_bot.rb:
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
FactoryBot.find_definitions
end
end
and in spec_helper.rb:
require 'support/factory_bot'
When I try to run the spec rake task, I get this error:
support/factory_bot.rb:2:in `block in <top (required)>': uninitialized constant FactoryBot (NameError)
What am I missing? This used to work fine when I was using the old factory_girl gem, but it has broken with the rename to factory_bot. Thanks!!
Doh. Silly mistake here, running bundle exec rake spec instead of rake spec solved it.
Also had to add require 'factory_bot' to the top of support/factory_bot.rb
Overview just in case you are doing this from scratch
installation rspec details here (basically add gem to Gemfile then run bundle install)
initialize RSPEC in your rails project rails g rspec:install
create new file your spec/support/factory_bot.rb add the following base code:
require 'factory_bot'
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
# RSpec without Rails
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
FactoryBot.find_definitions
end
end
add reference on spec/rails_helper.rb
require 'support/factory_bot'
as well as remove any fixture unused reference like this one
config.use_transactional_fixtures = true
That should be it!, finally run any spec file you want inside rspec default folders
e.g.:
spec/features/my_action_spec.rb
spec/models/my_model_spec.rb
spec/task/my_task_spec.rb
or run them all and check depending on your setup
rspec
rails rspec
bundle exec rspec
hope this helps someone with the whole RSPEC + FactoryBot Gem installation process
I had this problem too, remove the
require 'support/factory_bot'
There's a line on rails_helper, just uncomment it:
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
I had encountered and issue similar to this. I worked around it by removing the default testing suite ( MiniTest ). When you create a rails application and intend on using rspec and factory_bot, use the code below in the command line:
rails new myapp -T
Hope this helps xP
In my case I had to put those lines below 'require "rspec/rails" in file:
spec/rails_helper.rb:
like:
require "rspec/rails"
require_relative "support/factory_bot"
require_relative "support/chrome"

a concise recipe for installing, configuring and running minitest under autotest or Guard

In the past, I've run Rails + RSpec + autotest. Now I've upgraded to ruby 2.0 and I want to use minitest in a non-Rails environment (I'm using Padrino / DataMapper). I'm certain I'm not alone in wanting this.
What would be really useful is a concise recipe for installing and configuring things so the simple command:
$ autotest
or
$ bundle exec guard
will start testing everything under /test. I have searched SO and the InterWebs, and have yet to find such a recipe. A recipe should include:
what gems should you include in your Gemfile?
what commands do you run to set up the environment?
what configuration and support files do you need to create (Rakefile? .autotest? etc...)
a means for test files to require 'test_helper' to take care of repetitive functions
Extra credit for showing how to configure growl and spork for the full-on XP experience!
Mmm, I don't use autotest, nowadays seems that Guard is best fit, so:
# Add to Gemfile
group :development do
gem 'terminal-notifier-guard' # or libnotify for linux
gem 'rb-fsevent', require: false # or rb-inotify for linux
gem 'guard-minitest'
gem 'minitest'
end
# From bash
$ bundle update
$ guard init minitest # or bundle exec guard init minitest
# Edit the GuardFile, mine looks like:
guard 'minitest' do
# with Minitest::Unit
watch(%r|^test/(.*)\/?test_(.*)\.rb|)
watch(%r|^app/models/(.*)\.rb|) { |m| "test/test_#{m[1]}.rb" }
watch(%r|^lib/(.*)([^/]+)\.rb|) { |m| "test/test_#{m[2]}.rb" }
watch(%r|^test/helper\.rb|) { 'test' }
end
# Here my test helper.rb. /test/helper.rb
ENV['PADRINO_ENV'] ||= 'test'
require_relative '../config/boot'
require 'minitest/autorun'
# Have fun!
$ bundle exec guard

Unable to activate rspec-2.12.0, because rspec-core-2.13.1 conflicts with rspec-core (~> 2.12.0)

When I try to do rspec rspec_001.rb I get the above error
How can I get around the error and run tests?
contents of rspec_001.rb:
require 'rspec'
class Dummy < Object
end
describe "a test" do
end
I can't seem to use bundle exec rspec rspec_001.rb as this is not a Rails project with a Gemfile.
gem update rspec fixed this and now the spec runs ("No examples found." is ok, there aren't any) -
rspec rspec_001.rb
No examples found.
Finished in 0.00011 seconds
0 examples, 0 failures

Ruby: What does 'require: false' in Gemfile mean?

Does this:
gem 'whenever', require: false
mean that the gem needs to be installed, or does it mean it is not required?
This means install the gem, but do not call require when you start Bundler. So you will need to manually call
require "whenever"
if you want to use the library.
If you were to do
gem "whenever", require: "whereever"
then bundler would download the gem named whenever, but would call
require "whereever"
This is often used if the name of library to require is different than the name of the gem.
You use :require => false when you want the gem to be installed but not "required".
So in the example you gave:
gem 'whenever', :require => false
when someone runs bundle install the whenever gem would be installed as with gem install whenever. Whenever is used to create cron jobs by running a rake task but isn't usually used from within the rails (or other framework if not rails) application.
So you can use :require => false for anything that you need to run from the command line but don't need within your code.
require: false tells Bundler.require not to require that specific gem: the gem must be required explicitly via require 'gem'.
This option does not affect:
bundle install: the gem will get installed regardless
the require search path setup by bundler.
Bundler adds things to the path when you do either of:
Bundle.setup
which is called by require bundler/setup
which is called by bundle exec
Example
Gemfile
source 'https://rubygems.org'
gem 'haml'
gem 'faker', require: false
main.rb
# Fail because we haven't done Bundler.require yet.
# bundle exec does not automatically require anything for us,
# it only puts them in the require path.
begin Haml; rescue NameError; else raise; end
begin Faker; rescue NameError; else raise; end
# The Bundler object is automatically required on `bundle exec`.
Bundler.require
Haml
# Not required because of the require: false on the Gemfile.
# THIS is what `require: false` does.
begin Faker; rescue NameError; else raise; end
# Faker is in the path because Bundle.setup is done automatically
# when we use `bundle exec`. This is not affected by `require: false`.
require 'faker'
Faker
Then the following won't raise exceptions:
bundle install --path=.bundle
bundle exec ruby main.rb
On GitHub for you to play with it.
Rails usage
As explained in the initialization tutorial, the default Rails template runs on startup:
config/boot.rb
config/application.rb
config/boot.rb contains:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
which does the require 'bundler/setup' and sets up the require path.
config/application.rb does:
Bundler.require(:default, Rails.env)
which actually requires the gems.
Whenever you specify a Gem in your Gemfile and run bundle install, bundler will go and install specified gem and load code for that Gem in you app by putting require 'whenever' this way bundler will load code for all of your Gems in your Rails app, and you can call any method from any Gem without any pain, like you do most of the time.
but Gems like whenever, faker or capistrano are something which you do not need in your app code you need whenever code in your schedule.rb file to manage crons and capistrano code in deploy.rb file to customize deployment recipe so you need not to load code for these gems in your app code
and wherever you want to call any method from these Gems you can manually require thsese gems by yourself by putting require "whenever" . so you put :require => false in your Gemfile for these Gems, this way bundler will install that Gem but not load code for that Gem itself, you can do it whenever you want by simply putting like require 'whenever' in your case.
Analogy to Explain
## Gemfile
gem "university_degree", require: false
gem "dealing_with_boss"
"dealing_with_boss" - loaded into memory and ready to go.
degree gem - not "needed"....you need to manually require it, in order to use it.
In order to require gems in your Gemfile, you will need to call Bundler.require.
You can prevent bundler from requiring the gem with require: false, but it will still install and maintain the gem. Check this out for a more detailed explanation.

Getting Rspec + autotest working on windows

I have installed growl + rspec + autotest on my windows 7 machine. From the command prompt, when I type 'rspec spec/' it doesn't work. The tests will only run if I use 'rake spec/' + 'autotest'.
Also, I am running these tests: http://railstutorial.org/chapters/static-pages#code:default_pages_controller_spec (i.e. very, very trivial) and they are taking 8.11 seconds.
They also fail when I run them - even though they don't in the example. I have done everything the tutorial told me, the problem is the tutorial doesn't go too deep into installing rspec on a Windows machine. It gives a link, but even then you have to kinda piece the instructions together.
The errors I get are 'Failure/Error: Unable to find C to read failed line [31mundefined methord get' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x48336c0>'
The second error is very similar to that.
I have also installed Growl correctly, because I get a notification that there were two failures.
Can anyone help me?
I did a little googling, and according to this thread on the rspec ruby forum and this closed rspec-rails issue, this is an issue with rspec-rails that has been fixed.
I am running Ruby 1.9.2p136 on Windows 7 using rails 3.0.3.
This is what my Gemfile looked like, which shows the versions of rspec and rspec-rails that I was using:
source 'http://rubygems.org'
gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'
group :development do
gem 'rspec-rails', '2.4.1'
end
group :test do
gem 'rspec', '2.4.0'
gem 'webrat', '0.7.1'
end
I say "lookED like" because when I tried to run the rspec rails generator, this is what I got:
C:\Ruby\sample_app>rails generate rspec:install
create .rspec
create spec
create spec/spec_helper.rb
Could not find "autotest" in any of your source paths. Your current source paths
are:
C:/Ruby/sample_app/lib/templates/rspec/install
C:/Ruby/192-stackoverflow/lib/ruby/gems/1.9.1/gems/rspec-rails-2.3.0/lib/generators/rspec/install/templates
So then I added autotest to my Gemfile (and did bundle install again), then tried rails generate rspec:install again and it worked with no errors. So this is what my Gemfile looks like now:
source 'http://rubygems.org'
gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'
group :development do
gem 'autotest'
gem 'rspec-rails', '2.4.1'
end
group :test do
gem 'rspec', '2.4.0'
gem 'webrat', '0.7.1'
end
And the version of autotest that this installs is 4.4.6:
C:\Ruby\sample_app>bundle show autotest
C:/Ruby/192-stackoverflow/lib/ruby/gems/1.9.1/gems/autotest-4.4.6
I then created the controller as instructed in the tutorial:
$ rails generate controller Pages home contact
And I was able to run both "bundle exec autotest" and "rspec spec/" without getting the error you are seeing:
C:\Ruby\sample_app>bundle exec autotest
loading autotest/rspec2
bundle exec C:\Ruby\192-stackoverflow\bin\ruby -S C:/Ruby/192-stackoverflow/lib/ruby/gems/1.9.1/gems/rspec-core-2.4.0/bin/rspec --tty 'C:/Ruby/sample_app/spec/controllers/pages_controller_spec.rb'
..
Finished in 23.04 seconds
2 examples, 0 failures
# I killed autotest with CTRL-c at this point
Interrupt a second time to quit
Terminate batch job (Y/N)? y
Terminate batch job (Y/N)? y
C:\Ruby\sample_app>rspec spec/
..
Finished in 23.11 seconds
2 examples, 0 failures
I also continued on with the tutorial, writing specs for the About page, while autotest was running and it was running on my changes without any problems.
So please try:
Updating your Gemspec to look similar to my 2nd one posted here
Running 'bundle install'
Running 'bundle exec autotest'
and let me know if that works. I will be checking back!
I thought that this might help those who might be having trouble now that all the gems have been updated quite a bit (especially for those using Ruby on Rails 3 tutorial):
I was able to get this working using the latest versions of all gems:
My Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.6'
gem 'jquery-rails'
gem 'sqlite3', :group => [:development, :test]
gem 'pg', :group => :production #This is so Heroku will work
group :development do
gem 'rspec-rails'
end
group :test do
gem 'rspec'
gem 'webrat'
gem 'spork-rails' #Use this is only if you want to use spork
end
Make sure you clean up rspec if you've already got an older version (by using the Ruby on Rails 3 tutorial, for example):
https://stackoverflow.com/a/4433217/911133
To use autotest follow the directions here: https://github.com/svoop/autotest-growl
Note that installing growl-for-windows is part of that deal and snarl is not needed: http://www.growlforwindows.com/
Your .autotest file can be in one of two places
1) your HOME directory, which is (example):
C:\users\joeblow\.autotest
2) the rails application root (this will then operate for that app only)
my .autotest file looks like this:
require 'autotest/growl'
require 'autotest/restart'
require 'autotest/timestamp'
Autotest.add_hook :initialize do |autotest|
autotest.add_mapping(%r%^spec/(requrests)/.*rb$%) do
|filename, _|
filename
end
end
Autotest::Growl::clear_terminal = false
Make sure you've done a 'bundle install'
Then run Growl for windows (start menu or start on windows boot)
run autotest in the command line and you should be good to go!
c:\users\joeblow\workspace\Rails\MyRailsProject> autotest
I've not found a permanent fix that works yet, but apparently it boils down to a path issue - something is munging the windows path and it breaks. However, there's a work around:
Within your describe, before the 'get' call, put this:
include RSpec::Rails::ControllerExampleGroup
Here's sample code using a generated Rails spec for a controller. Note that it's at the beginning of the scope:
require 'spec_helper'
describe PagesController do
include RSpec::Rails::ControllerExampleGroup
describe "GET 'home'" do
it "should be successful" do
get 'home'
response.should be_success
end
end
describe "GET 'contact'" do
it "should be successful" do
get 'contact'
response.should be_success
end
end
end
There's a fix I've seen that suggests a change to spec_helper (in the Rails case), but I couldn't get it to work.
EDIT: A bit more research reveals this is a problem with autospec - this work around will work if you're just using rspec, but will not work with autotest. I've not been able to find a solution for this, however.

Resources