How to run single test class using minitest in ROR - ruby-on-rails

My Gemfile looks like this:-
group :test do
# Pretty printed test output
gem 'capybara'#,'1.1.2'
gem 'cucumber-rails','1.2.1'
gem 'cucumber','1.1.4'
gem 'rspec-rails','2.8.1'
gem 'rspec-cells','0.1.2'
gem "factory_girl_rails"
gem "guard-rspec"
gem "minitest"
gem 'headless'
gem 'minitest-rails'
gem 'minitest-rails-capybara'
end
minitest_helper.rb looks like :-
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "minitest/autorun"
require "capybara/rails"
class ControllerTest < MiniTest::Spec
include Rails.application.routes.url_helpers
include Capybara::DSL
register_spec_type(/integration$/, self)
end
And my products_controller_test.rb looks like this:-
require "minitest_helper"
describe "Products Controller" do
it "shows product's name" do
uname="Glasses"
product1 = Product.create!(:name => uname, :description => uname, :no_of_items => 3,:fee_percentage => 4)
visit products_path
page.text.must_include "Glasses"
end
end
BUT..after executing ruby -Itest test/controllers/products_controller_test.rb
I get no error,no indication to show that this test class has been loaded :-
ruby -Itest test/controllers/products_controller_test.rb
:public is no longer used to avoid overloading Module#public, use :public_folder instead
from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/resque-1.19.0/lib/resque/server.rb:12:in `<class:Server>'
Loaded suite test/controllers/products_controller_test
Started
Finished in 0.004953 seconds.
0 tests, 0 assertions, 0 failures, 0 errors, 0 skips
its first time i am using Minitest...

Your Gemfile is a little heavy... If you remove all the RSpec references, you'll run just fine.
(The "describe" and "it" methods are being usurped by rspec)
Remove:
gem 'rspec-rails','2.8.1'
gem 'rspec-cells','0.1.2'

Related

undefined method `expect' for #<Spinach::Features

I've followed the README at the spinach repo as well as including spinach-rails instead of the base spinach gem.
Spinach documentation states:
# When using Capybara, you can switch the driver to use another one with
# javascript capabilities (Selenium, Poltergeist, capybara-webkit, ...)
#
# Spinach already integrates with Capybara if you add
# `require spinach/capybara` in `features/support/env.rb`.
Which I have done:
Head of my env.rb file:
require 'spinach-rails'
require 'spinach/capybara'
ENV['RAILS_ENV'] = 'feature'
require 'rspec'
require 'factory_girl_rails'
require 'webmock'
require 'coffee_script'
include WebMock::API
WebMock.disable_net_connect!(:allow_localhost => true)
require_relative '../../config/environment'
The step failing in the test reads:
step 'I see the Generals Page' do
expect(page).to have_content("Inventory")
end
When I inspect the Spinach::FeatureSteps class using RubyMine I can see two hits - one to the "base" class and the other to the capybara version:
require 'capybara'
require 'capybara/dsl'
require 'rbconfig'
require 'spinach/config'
require_relative 'feature_steps'
module Spinach
class FeatureSteps
# Spinach's capybara module makes Capybara DSL available in all features.
#
# #example
# require 'spinach/capybara'
# class CapybaraFeature < Spinach::FeatureSteps
# Given "I go to the home page" do
# visit '/'
# end
# end
#
module Capybara
include ::Capybara::DSL
Which really makes it seem like there should be a switch of sorts in the spinach configuration that lets me choose to use the capybara DSL in my tests.
But it doesn't appear to be working properly.
How can I get Capybara working with Spinach?
Gemfile.lock:
spinach (0.8.10)
colorize
gherkin-ruby (>= 0.3.2)
json
spinach-rails (0.2.1)
capybara (>= 2.0.0)
railties (>= 3)
spinach (>= 0.4)
test and feature group in Gemfile:
group :test, :feature do
gem "factory_girl_rails"
gem "capybara"
gem "webmock"
gem "capybara-webkit"
gem "spinach-rails"
end

my tests don't run with minitest

I'm totally new in testing and after two years of rails development, it has to change!
Therefore, I'm trying to install minitest on a rails 4 application.
I did the following:
updated my gemfile:
group :test do
gem 'factory_girl'
gem 'minitest-rails'
gem 'minitest-rails-capybara'
gem 'minitest-colorize'
gem 'minitest-focus'
gem "shoulda-matchers"
gem "guard-rspec"
end
created a helper in test/test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
#require "minitest/rails"
require "minitest/spec"
require 'minitest/focus'
# To add Capybara feature tests add `gem "minitest-rails-capybara"`
# to the test group in the Gemfile and uncomment the following:
require "minitest/rails/capybara"
# Uncomment for awesome colorful output
require "minitest/pride"
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
ActiveRecord::Migration.check_pending!
fixtures :all
extend MiniTest::Spec::DSL
#use ActiveSupport::TestCase when describing an ActiveRecord model
register_spec_type self do |desc|
desc < ActiveRecord::Base if desc.is_a? Class
end
# Add more helper methods to be used by all tests here...
def self.prepare
# Add code that needs to be executed before test suite start
end
prepare
def setup
# Add code that need to be executed before each test
end
def teardown
# Add code that need to be executed after each test
end
end
generated a scaffold to have some "test" testfiles, like this one:
models/project_test.rb
require "test_helper"
describe Project do
before do
#project = Project.new
end
it "must be valid" do
#project.valid?.must_equal true
end
end
when I type rake minitest:models in terminal, this is what I get:
Run options: --seed 40421
# Running tests:
Fabulous tests in 0.049207s, 0.0000 tests/s, 0.0000 assertions/s.
0 tests, 0 assertions, 0 failures, 0 errors, 0 skips
Apparently, minitest runs but my tests are not executed. What's wrong?
Thanks!!!
The issue was due to a conflict with rspec which was added as a dependency by guard-rspec.
many thanks to #blowmage!

Factory already registered: user (FactoryGirl::DuplicateDefinitionError)

Description of problem:
- I've setup factory_girl_rails however whenever I try and load a factory it's trying to load it multiple times.
Environment:
- rails (3.2.1)
- factory_girl (2.5.2)
- factory_girl_rails (1.6.0)
- ruby-1.9.3-p0 [ x86_64 ]
> rake spec --trace
** Execute environment
-- Creating User Factory
-- Creating User Factory
rake aborted!
Factory already registered: user
The only other thing I've changed is:
/config/initializers/generator.rb
Rails.application.config.generators do |g|
g.test_framework = :rspec
g.fixture_replacement :factory_girl
end
GEMFILE
gem 'rails', '3.2.1'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'devise'
gem 'haml-rails'
group :development do
gem 'hpricot'
gem 'ruby_parser'
gem "rspec-rails"
end
group :test do
gem "rspec"
gem 'factory_girl_rails'
end
gem 'refinerycms-core', :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-dashboard', :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-images', :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-pages', :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-resources', :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-settings', :git => 'git://github.com/resolve/refinerycms.git'
group :development, :test do
gem 'refinerycms-testing', :git => 'git://github.com/resolve/refinerycms.git'
end
gem 'refinerycms-inventories', :path => 'vendor/engines'
FactoryGirl.define do
factory :role do
title "MyString"
end
end
This seems to be a compatibility/environment issue that I can't seem to figure out. Any suggestions?
EDIT: here's my spec/spec_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
#require 'factory_girl_rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
### Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
#config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
end
The gem factory_girl_rails should be required in the spec_helper.rb rather than the gemfile - it is possible that you are requiring FactoryGirl twice which is why you are getting the duplicate.
Try this in your gem file:
group :test do
gem "rspec"
gem 'factory_girl_rails', :require => false
end
Then make sure that factory girl is required in the spec_helper with:
require 'factory_girl_rails'
By the way - you don't need both rspec and rpsec-rails in your gemfile. You can replace both with the following:
group :development, :test do
gem 'rspec-rails'
end
You need rspec in both groups so that the rake tasks will work in development and the core testing will work in test.
I had the same problem recently. In my case one of the files in /factories had a _spec.rb ending (result of creative cp use). It was loading twice, first by rspec and then as a factory.
Is there any chance you pasted this whole snippet for the support file from the config docs?
# RSpec
# spec/support/factory_girl.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
# RSpec without Rails
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
FactoryGirl.find_definitions
end
end
If you read the comments you'll see you only want one block or the other. I made this mistake and got the error stated in the question.
I had this problem too. In my case there were two files with the same code, like this:
FactoryGirl.define do
factory :user do
end
end
One file was named "Useres.rb" and the other "User.rb" so I just deleted "Useres.rb" and fixed the error.
Call FactoryGirl.define(:user) or FactoryGirl.find_definitions twice you also have this problem.
Try removing the second call or:
FactoryGirl.factories.clear
FactoryGirl.find_definitions
Another possible reason is spare call of FactoryGirl.find_definitions.
Try to remove find_definitions if found.
Make sure your individual factory files are not ending with _spec.
https://github.com/thoughtbot/factory_girl/issues/638
Loading factory girl into a development console will do this too:
require 'factory_girl_rails'; reload!; FactoryGirl.factories.clear; FactoryGirl.find_definitions
will raise a FactoryGirl::DuplicateDefinitionError on a sequence under Factory Girl v4.4.0.
It seems the sequences get handled differently within FG and simply wrapping all sequences in a rescue block will solve the issue.
For example:
begin
sequence :a_sequence do |n|
n
end
sequence :another_sequence do |n|
n*2
end
rescue FactoryGirl::DuplicateDefinitionError => e
warn "#{e.message}"
end
I have the same the problem. What I do is move the spec/factories.rb to spec/factories/role.rb
I renamed spec/factories as spec/setup_data and the problem gone.
Try renaming the spec/factories to anything that suites you, should work.
I had the same problem- make sure you aren't loading FactoryGirl a second time in your spec/support/env.rb file.
I had same problem. This happens becouse of you using gem 'refinerycms-testing'? wich requires factory-girl, so you should commit this gem, or commit gem 'factory_girl_rails', don't use all of this gems.
#gem 'refinerycms-testing', '~> 2.0.9', :group => :test
gem 'factory_girl_rails', :group => :test
or
#gem 'factory_girl_rails', :group => :test
gem 'refinerycms-testing', '~> 2.0.9', :group => :test
Please try following these steps
1) I looked for all occurrences of "factory_girl" from my RAILS_ROOT:
find . -name "*.rb" | xargs grep "factory_girl"
2) Because this was a full engine plugin "app" that I created via "rails plugin new --mountable", I had a file under RAILS_ROOT//lib/ called "engine.rb". It had:
config.generators do |g|
g.test_framework :rspec, :fixture => false
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
g.assets false
g.helper false
end
3) I also had the following in my spec_helper.rb file:
Dir["#{File.dirname(FILE)}/factories/*/.rb"].each { |f| require f }
4) the g.fixture_replacement line in engine.rb and the Dir line in spec_helper.rb were initializing the factories twice. I commented out the one from spec_helper.rb and that fixed the problem.
Alternatively, you can leave in spec_helper.rb and comment out in engine.rb.
Both fixed the problem in my case.
I had exactly the same problem.
It occurs when you use the scaffold generator.
It automatically creates a factory in test/factories/
So generally just deleting this file solve your issue
I had the same problem, it turned out there was a default users.rb created inside the test/factories which was created by the rails g command. This file was causing the conflict. The error went away when I deleted the file.
try to run
rake db:test:prepare
I just found I was getting this answer when accidentally calling cucumber features. When I just called cucumber, the problem went away.
I also ran with the same issue and commenting out a single line in spec_helper.rb file solved my problem.
Try commenting out this line from spec_helper.rb file and you should be good.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
I defined the same name factory at factories.rb, and I just found that someone else define the same factory below the directory of factories. So actually I can just use it without define another one.
Replace the refinerycms-testing gem with rspec-rails and factory_girl_rails
Check to see if you added factories through the model generator. My generator made a model and I added one to my main factory.rb file. Deleting the automatically generated ones worked for me.
In my case,
First my co-worker has setup the project with factory_girl gem with
Dir[Rails.root.join('spec/factories/**/*.rb')].each { |f| require f }
in rails_helper.
After some days, I replaced the gem with factory_girl_rails. Since this new gem also does that internally so factories were registered twice. This was causing the error.
Removed that line from rails_helper and it worked.
I solved this because I was trying to create two factories. My feature spec included the line:
let!(:user) { create(:user) }
And then I used a sign_up(user) helper method:
def sign_up(user)
visit '/users/sign_up'
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
fill_in 'Password confirmation', with: user.password_confirmation
click_button 'Sign up'
end
Back to my feature spec, I called:
context 'logging out' do
before do
sign_up(user)
end
...
thus effectively trying to sign up a User that was already being created by the factory.
I altered the sign_up(user) to sign_in(user), and the helper to:
def sign_in(user)
visit '/users/sign_in'
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Log in'
end
now the user argument creates the User in the db due to the let! block and the sign_up(user) logs them in.
Hope this helps someone!
oh! and I also had to comment out:
Dir[Rails.root.join('spec/factories/**/*.rb')].each { |f| require f }
as a lot of the other answers suggest.
The strangest thing, I got this error with the following syntax error in the code:
before_validation :generate_reference, :on: :create
:on: was causing this error. How or why will remain a mystery.
I resolved it by removing spec/factories/xxx.rb from command line:
rspec spec/factories/xxx.rb spec/model/xxx.rb # before
rspec spec/model/xxx.rb # after
for me, this issue was coming because was using both gems
gem 'factory_bot_rails'
gem 'factory_girl_rails'
to solve I removed gem 'factory_bot_rails' from gem file.
and also added require 'factory_girl' to spec/factories/track.rb file.
if Rails.env.test?
require 'factory_girl'
FactoryGirl.define do
factory :track do
id 1
name "nurburgring"
surface_type "snow"
time_zone "CET"
end
end
I hope this will help.
I solved this issue by just adding required: false to gem 'factory_bot_rails' like so:
gem 'factory_bot_rails', require: false
Check that you don't have multiple factories with same name this is one of reasons which causes error
Attempting to define multiple factories with the same name will raise an error.

Cucumber: Factory Girl doesn't modify database -- creates object with .create but database table is still empty afterwards

p = Factory(:model)
ap Model.find(:all) #output to prove that it's getting created
so... the print shows that the IDs of the objects is going up.... but the database remains empty as I continually refresh the view on MySQL workbench -- so my cucumber tests fail, because the controllers pull stuff from the database... but there is nothing in the database! =(
My Gem file: test
group :test do
gem "cucumber", "~>0.10.3"
gem "cucumber-rails", "0.3.2"
gem "launchy"
gem "hpricot"
gem "gherkin", "~>2.4.0"
gem "capybara", "0.4.1.2"
gem "rspec", "1.3.2"
gem "rspec-rails", "1.3.2"
gem "rspec-core"
gem "rspec-expectations"
gem "webrat", "0.7.0"
gem "database_cleaner"
gem "factory_girl", "1.2.4"
gem "shoulda", :require => nil
gem "shoulda-matchers", :git => "https://github.com/thoughtbot/shoulda-matchers"
gem "awesome_print"
gem "cobravsmongoose"
end
My Requires for env.rb (cucumber env)
ENV["RAILS_ENV"] = 'test'
ENV["RACK_ENV"] = 'test'
BASE_DOMAIN = "myapp.dev" #using POW
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'cucumber/rails/rspec'
require 'rake'
require 'shoulda'
require 'factory_girl'
require 'factory_girl/step_definitions'
require 'awesome_print'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
And in envs/test.rb
Bundler.require(:test) #just in case I forgot something
EDIT:
Some console output
Factory(:model).errors =>
#<ActiveRecord::Errors:0x10c5a6498 #base=#<ModelName id: 1, name: "Ready or not", status: 0, account_id: 2, user_id: 1, created_at: "2011-09-08 15:09:05", updated_at: "2011-09-08 15:09:05", description: "Things are not as they used to be", value: #<BigDecimal:10cb2c188,'0.12345E5',9(18)>, category_id: nil, allow_downloads: true, visibility: 1, locked: nil>, #errors=#<OrderedHash {}>>
And looking at the console during runtime, this object is def getting in INSERT INTO command... but there is this:
RELEASE SAVEPOINT active_record_1
SQL (1.3ms) ROLLBACK
which I feel might be what is causing the problem.... some sort of pre-emptive rollback.
Try this then:
in env.rb
require 'database_cleaner'
require 'database_cleaner/cucumber'
DatabaseCleaner.strategy = nil
in features/support/env.rb make sure that you have
# This will prevent the deletion of the data written in the test db until the end of the
# cucumber feature
Cucumber::Rails::World.use_transactional_fixtures = false
by default this is true so it looks like nothing goes in the db.
I would begin by seeing if there are any validation errors when the object is being saved, ie
p Factory(:model).errors
and then, if there are none, to start watching what active record does by adding a logger to stdout:
ActiveRecord::Base.logger = Logger.new(STDOUT)
and using that to make sure the data is being written to the db.
Past those things, I would try updating to the 2.1 version of FactoryGirl and seeing if that makes a difference.
In the file features/support/env.rb, you should set
DatabaseCleaner.strategy = :truncation

assigns_to doesn't work for Rails 3 Shoulda on Ubuntu

I'm using Rails3 with rspec and shoulda. I have the below spec
describe PagesController, "on GET to show while logged off" do
before(:each) do
#site = Factory.create(:site)
#site.domains << Factory.create(:domain)
#site.save!
#site.pages << Factory.create(:page)
#site.menus << Factory.create(:menu, {:site=>#site, :is_visible=>true})
#site.menus << Factory.create(:menu, {:site=>#site, :is_visible=>true})
#site.menus << Factory.create(:menu, {:is_visible=>false, :site=>#site})
get :show
end
it { should render_template(:show) }
it { should render_template('layouts/2col') }
it { should assign_to(:site) }
it { should assign_to(:site).with(#site) }
it { should assign_to(:site).with(#site) }
it { should assign_to(:page).with(#site.pages[0])}
it "show visible menu_items only" do
assert assigns[:menu_items].length == 2
end
end
Here's my Gem File
group :development, :test do
gem 'autotest'
gem 'factory_girl'
gem 'rspec', '>=2.0.0.beta.19'
gem 'rspec-rails', '>=2.0.0.beta.17'
gem 'shoulda'
end
and here's my spec_helper
require 'rspec/rails'
require 'shoulda'
require 'shoulda/integrations/rspec2'
require 'authlogic/test_case'
require 'factory_girl
Ok so far everything pretty close matches what I've seen before, however whenever I run my tests I get the errors like below
1) PagesController on GET to show while logged off
Failure/Error: it { should assign_to(:site) }
Expected action to assign a value for #site
# ./spec/controllers/pages_controller_spec.rb:19
No my first thought was that the code was broken, however the application runs correcty. Also if I test that the values are assigned by using the assigns[:site] then the test passes.
Has anyone any idea what I need to change in order to make these tests start working again.
Thanks In Advance
Andy
You need to call subject { controller } before your it statements. This actually confused me so badly for a while that I wrote my first ever blog post about it.
If you are using Ruby 1.9.2 the assign_to matcher with the shoulda-matchers gem version lower than 1.0.0beta2 will still not work, even if you include the subject { controller } (which, I believe, is not really needed).
It's caused by a change in Ruby 1.9.2. Here is the bugreport for shoulda. The fix is already included and released in shoulda-matchers version 1.0.0beta2.
So just have this in your Gemfile:
group :development, :test do
gem 'shoulda-matchers'
...
and update to the latest version (1.0.0.beta2 atm):
bundle update shoulda-matchers

Resources