I have a Rails application using Rails 3.
I added rspec-rails to my Gemfile:
group :development, :test do
gem 'rspec-rails'
end
and then I run bundle install. It shows my gem list, and all rspec gems are there (core, rails, etc.).
However, when I run
rails g rspec:install
that's what it returns:
create .rspec
create spec
create spec/spec_helper.rb
Although I have models and controllers in my application, it just create those files. Why isn't Rspec creating the spec files?
This is no longer true, and you can set the generator to create RSpec spec files when generating new parts of your rails application, as well as creating spec files for existing sections of the app.
The main feature lies in the application's generator configuration which is enabled when running the rspec-rails rspec:install task, but if you want to specify specific spec files to include/exclude, you may want this:
config/environments/development.rb // or any env you want
Rails.application.configure do
...
config.generators do |g|
g.test_framework :rspec
g.fixture_replacement :factory_bot
g.factory_bot dir: 'spec/factories'
g.controller_specs false
g.request_specs true
g.helper_specs false
g.feature_specs true
g.mailer_specs true
g.model_specs true
g.observer_specs false
g.routing_specs false
g.view_specs false
end
end
Generator Settings
The 'test_framework' option allows the rails to know exactly what test framework to create test files for, and generate new files based on your settings.
With the 'fixture_replacement', we can keep rails from generating fixtures by default, and instead create factories with each model created.
Lastly are the 'factory_bot' options, where you can change the factory folder default if needed, but will default to this directory on install. You can find more options in the Factory Girl/Bot Instructions.
Now when we generate something new, like a model:
> rails g model settings
invoke active_record
create db/migrate/20170915173537_create_settings.rb
create app/models/setting.rb
invoke rspec
create spec/models/setting_spec.rb
invoke factory_girl
create spec/factories/settings.rb
Generating Spec Files For Pre-Generated Sections of the App
Similar to generating rails files, you can generate spec files through Rspec's own task:
> rails g rspec:model old_settings
create spec/models/old_settings_spec.rb
invoke factory_girl
create spec/factories/old_settings.rb
This command uses the same conventions as the rails' generate command to create spec files, including scaffold, so you can create spec files for an entire namespace.
Rspec doesn't automatically create specs for your existing models and controllers. You'll have to go create those files yourself now.
Creating a spec file is really easy. Just make a file ending in _spec.rb and put this in it:
require 'spec_helper';
describe User do;
end
(of course replacing User with the class you are testing) and you're there.
As a footnote, if your generator command does not generate a file you expect, check the application.rb config file to make sure specific specs were not disabled.
For me following generator did not create file as expected.
% bin/rails g rspec:request api
Running via Spring preloader in process 70924
%
because in application.rb
g.request_specs false
was set. While this seems obvious after the fact, command output is not intuitive. Setting it to true and re-running the generator produces expected result.
% bin/rails g rspec:request api
Running via Spring preloader in process 71843
create spec/requests/apis_spec.rb
Related
I'm making a gem that executes Rails commands (rails g model Item for example). When I use it in a Rails project, everything works. The problem is testing it in development outside of a Rails project.
I'm using cucumber with aruba to test if CLI commands execute the proper rails commands and generate the expected files. Unfortunately, when I try to test the behaviour it fails because there are no rails files and the commands require to be run inside of a Rails project in order to work.
I have added a rails dependency to the gemspec:
Gem::Specification.new do |spec|
spec.add_development_dependency 'rails', '~> 5.2.4'
end
I've thought about creating a new rails project on test start and then deleting it after the tests run, but that seems highly inconvenient. Is there a better way to do this?
A technique we use for WickedPDF is in the default rake task, before we run the tests, is to delete & generate a full Rails application in a gitignored subdirectory of the gem.
As a high-level simplified example of this Rakefile, it looks something like this:
Rakefile
require 'rake'
require 'rake/testtask'
# This gets run when you run `bin/rake` or `bundle exec rake` without specifying a task.
task :default => [:generate_dummy_rails_app, :test]
desc 'generate a rails app inside the test directory to get access to it'
task :generate_dummy_rails_app do
if File.exist?('test/dummy/config/environment.rb')
FileUtils.rm_r Dir.glob('test/dummy/')
end
system('rails new test/dummy --database=sqlite3')
system('touch test/dummy/db/schema.rb')
FileUtils.cp 'test/fixtures/database.yml', 'test/dummy/config/'
FileUtils.rm_r Dir.glob('test/dummy/test/*') # clobber existing tests
end
desc 'run tests in the test directory, which includes the generated rails app'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
Then, in test/test_helper.rb, we require the generated Rails app, which loads Rails itself and it's environment:
test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'test/unit' # or possibly rspec/minispec
# Tests can go here, or other test files can require this file to have the Rails environment available to them.
# Some tests may need to copy assets/fixtures/controllers into the dummy app before being run. That can happen here, or in your test setup.
You could skip parts of Rails that aren't needed by customizing the command that generates the app. For example, your gem may not need a database at all or a lot of things by default, so you command could be customized for a simpler app. Something like this maybe:
system("rails new test/dummy --skip-active-record \
--skip-active-storage --skip-action-cable --skip-webpack-install \
--skip-git --skip-sprockets --skip-javascript --skip-turbolinks")
In the WickedPDF project, we wanted to test across a wide range of "default" Rails installs, so we don't customize the command much, but that may generate much more than what you need to test some generator tasks.
WickedPDF also tests against multiple versions of Rails with TravisCI and multiple Gemfiles, but this could also be accomplished with the Appraisal gem that Luke suggested in this thread.
Check out Thoughbot's Appraisal gem:
Appraisal integrates with bundler and rake to test your library against different versions of dependencies in repeatable scenarios called "appraisals."
Here is a guide on how to set it up, including setting up a micro Rails app within your tests dir.
I am new to ruby and Ruby on Rails. I used command rails new [project name] to create a new rails project, and when using rails generate scaffold [Model name] to create a model, rails itself always create a testing module related to the model and the controller. so, how do i remove all rails default testing module and replace with some custom testing modules like Rspec?
If you have gem rspec-rails in your Gemfile, and don't have minitest, then rails generators already informed that you use Rspec instead of Minitest. rails generate command will create specs instead of tests.
Off-topic: it creates fixtures as well. If instead of fixtures you use factories you need to declare it to your config-file:
# config/application.rb
config.generators do |g|
g.factory_bot dir: 'spec/factories'
end
I have a Rails 4.1 project that uses RSpec and Cucumber.
I've recently added fixture_builder.
fixture_builder.rb includes logic to rebuild fixtures any time the file changes.
This works fine for RSpec with require 'fixture_builder' in spec_helper.rb.
However, when running Cucumber tests fixture_builder.rb is not called, so fixtures are not updated if any changes have been made to fixture_builder.rb.
Is there an equivalent config file like spec_helper.rb for Cucumber?
By default, Cucumber loads all *.rb files in the same directory as the feature(s) it's running and all subdirectories of that directory, so you can put your require in any file you want in any of those directories.
The conventional thing to do is to put 'support' code like require in features/support/env.rb, or in another file in features/support if your env.rb gets too big.
The cucumber-rails gem provides a generator that sets up Cucumber to work with Rails. If you haven't already, install the gem and run
rails g cucumber:install
to create features/support/env.rb and the rest of the usual Rails + Cucumber setup.
I started making a Rails 3.1 engine, and I'm having a hard time testing it using rspec.
First of all, if I run rails g integration_test whatever it creates a regular integration test in tests/integration instead of spec/requests (the rspec-rails gem is installed and required as a development dependency in the gemspec file)
Also, when I run a spec test I get an error saying the table corresponding to the model I'm testing has not been created. I tried rake engine_name:install:migrations and running rake db:migrate from inside the dummy app, and I get a "table already exists" error.
Everything just seems disconnected, I feel I'm missing something here to make the rspec gem work seamlessly as it usually does with full rails applications.
I followed all the changes from here http://rubyx.com/2011/03/01/start-your-engines and I can test the engine manually by launching the dummy app via the console as shown here http://railscasts.com/episodes/277-mountable-engines.
Is there a way to make rspec the default for testing a rails 3.1 engine?
I am using RSpec with a Rails engine without issues.
I created my plugin using the following switches: -T --full --dummy-path=spec/dummy.
-T excludes test/unit
--full indicates that the plugin is an engine
--dummy-path is simply so that we don't get a test directory (the
default is test/dummy).
From there I used the spec_helper from the "start your engines" article:
# Configure Rails Envinronment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../')
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
For the generators. I add a config.generators block to my engine.rb file like so:
module MyEngine
class Engine < Rails::Engine
config.generators do |g|
g.test_framework :rspec, :view_specs => false
end
end
end
With that, I'm able to get rspec tests when running a generator like the model generator.
As for the DB, is your database.yml file set up correctly? Did you load the test environment, e.g. rake db:test:clone or rake db:migrate RAILS_ENV=test? My guess is that RSpec can't see your tables because there isn't a test database set up.
I was looking for the same answer and I found the combustion gem* which promise to setup a full environment for spec'ing your engine in a simpler way. Just add
gem.add_development_dependency 'combustion', '~> 0.3.1'
to your gemspec and run
bundle exec combust
to reproduce a full rails app in your spec directory.
*I haven't tried it yet...
I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec. In order to test the engine a rails 3 app is necessary. Here is what I am currently doing:
Add a rails test app to the root of the gem (myengine) by running: rails new /myengine/rails_app
Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app
Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile
Add spec to the root directory of the gem: /myengine/spec
Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:
env.rb:
Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)
Do you see any problems with setting it up like this? The tests run fine, but I am a bit hesitant to put the features inside the test rails app. I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.
If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.
**UPDATE
I changed my setup a bit since I wrote this question. I decided to get rid of the spec directory under the root of the engine. Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app. Then I include the gem like I did in step #3 above. Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app. I am still interested in hearing if anyone has a different setup.
Rails 3.1 (will) generate a pretty good scaffold for engines. I'd recommend using RVM to create a new gemset called edge and switch to it:
rvm gemset create edge
rvm use #edge
Then install edge rails:
git clone git://github.com/rails/rails.git
cd rails
rake install
From there, you can follow Piotr Sarnacki's mountable app tutorial, replacing calls such as:
bundle exec ./bin/rails plugin new ../blog --edge --mountable
With simply:
rails plugin new blog --mountable --full
The mountable option makes the application mountable, whilst the full option makes it an engine with tests already built-in. To test the engine, this generator generates a folder in test called dummy which contains a small Rails application. You can see how this is loaded in test/test_helper.rb.
Then it's up to you to massage the data to do what it needs to in order to work. I would recommend copying over the cucumber files from a standard rails g cucumber:install into the project and then messing about with it until it works. I've done this once before so I know it's possible, but I cannot find the code right now.
Let me know how you go.
I'll explain how I did it using as example the following gem: https://github.com/skozlov/netzke-core
The testing application. It is in netzke-core/test/rails_app. This app can be run independently, so I can also use it for manual testing or for playing around with new features if I like.
In order for the testing app to load the gem itself, I have the following in application.rb:
$:.unshift File.expand_path('../../../../lib', __FILE__)
require 'netzke-core'
Cucumber features. They are in netzke-core/features. In env.rb I have:
require File.expand_path(File.dirname(__FILE__) + '/../../test/rails_app/config/environment')
... which will load the testing application before executing the features.
Specs. These are in netzke-core/spec. In spec_helper.rb I have the following:
require File.expand_path("../../test/rails_app/config/environment", __FILE__)
... which will load the testing application before running the specs.
Running tests. This setup lets me run the tests from the root of the gem:
cucumber features
and
rspec spec
Factory Girl. Not for this particular gem, but I'm normally using factory_girl instead of fixtures (see, for example, a similar setup in https://github.com/skozlov/netzke-basepack).
A bit late to the party, but here is my strategy:
Generating the rails plugin in 3.2:
rails plugin new blog --mountable --full
This creates test/dummy, containing the dummy rails app
Add the specs to spec
Move the dummy folder to spec (and optionally get rid of the other testfiles)
Adapt specs/spec_helper.rb so it includes
require File.expand_path("../.../config/environment", __FILE__)
instead of
require File.expand_path("../dummy/config/environment", __FILE__)
Execute rails g cucumber:install. It will generate features folder a.o.
Add
ENV["RAILS_ROOT"] ||= File.expand_path(File.dirname(__FILE__) + '/../../spec/dummy')
before
require 'cucumber/rails'
in features/support/env.rb
Now you have features and spec in the root of you project, while the dummy rails app is neatly tucked away under spec/dummy