undefined method `use_transactional_fixtures - ruby-on-rails

I was following a long with this tutorial on how to test rails apps and I came across this error:
/home/***/***/***/spec/spec_helper.rb:27:in `block in <top (required)>': undefined method `use_transactional_fixtures=' for #<RSpec::Core::Configuration:0x9fe8824> (NoMethodError)
My gems are as follows:
gem "rspec-rails", :group => [:test, :development]
group :test do
gem "factory_girl_rails"
gem "capybara"
gem "guard-rspec"
end
and my config file is as follows:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
# 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
# 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
so why am I getting this error when ever guard is run?

Might be because you are not using ActiveRecord (e.g you are using MongoId) and if that's the case you need to comment out *config.use_transactional_fixtures* in spec_helper
spec_helper.rb
# 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

Related

Rspec undefined method `expects' for Object

I have recently upgraded my ruby on rails project to rails 5.0.7 and ruby 2.5.1 and I am getting an RSPEC error undefined methodexpects' for` different objects I am testing.
I have tried adding a configuration in the spec_helper.rb file as suggested here (although I did a quick search and didn't find :should defined anywhere), here and here:
config.expect_with :rspec do |expectations|
expectations.syntax = [:expect, :expects]
end
Also tried including include RSpec::Matchers in my spec_helper.rb, but then I get even more errors:
`only the `receive`, `have_received` and `receive_messages` matchers are supported with `expect(...).to`, but you have provided: #<RSpec::Matchers::BuiltIn::Eq:0x00007f962b3db058>`
An example of how I am using expect:
describe "process" do
before :each do
#item = Item.new
end
it "parses the uploaded file and extract the correct report data" do
item_a_data = {"name" => "one"}
item_b_data = {"name" => "two"}
file_contents = {"items" => [item_a_data, item_b_data]}
#item.data_file = double("file", :read => file_contents.to_json)
#item.name = item_a_data["name"]
#item.expects(:interpret_json_file).with(#item.data_file).returns(file_contents)
#item.expects(:save).returns(true)
expect(#item.process_data_file).to be_truthy
expect(#item.data).to eq item_a_data.to_json
end
Notice that the error occurs when I call #item.expects
In my Gemfile I have the following gems (among others):
group :development, :test do
gem 'byebug'
gem 'sqlite3'
gem 'rspec-rails'
gem 'rb-fsevent', '~> 0.9.1'
gem 'guard-rspec', '4.7.3'
gem 'guard-spork', '2.1.0'
gem 'spork', '0.9.2'
gem 'jasmine-rails'
gem 'teaspoon-jasmine'
end
group :test do
gem 'capybara'
gem 'cucumber-rails', :require => false
gem 'database_cleaner'
gem 'factory_girl_rails', '4.1.0'
gem 'launchy'
gem 'poltergeist'
gem 'timecop'
gem 'webmock'
gem 'simplecov', '~> 0.16.0'
gem 'rails-controller-testing'
end
spec_helper.rb:
require 'rubygems'
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'
Spork.prefork do
require 'simplecov'
SimpleCov.start 'rails'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'devise'
require './spec/controllers/controller_helpers.rb'
# 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|
config.include Devise::Test::ControllerHelpers, type: :controller
config.include ControllerHelpers, type: :controller
config.include Capybara::DSL
# 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
config.infer_spec_type_from_file_location!
# 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"
config.include FactoryGirl::Syntax::Methods
# config.expect_with :rspec do |expectations|
# expectations.syntax = :expect
# end
end
end
Spork.each_run do
# This code will be run each time you run your specs.
end
The solution would be to re-write it to the following syntax:
expect(#item).to receive(:interpret_json_file).with(#item.data_file) { file_contents }
expect(#item).to receive(:save) { true }
Basically ActiveRecord model does not know about rspec expectations and it should not. If that specs were working before then you might used some decoration for ActiveRecord models and that is why it worked previously.

What am I doing wrong in Shoulda Matchers?

In gem file I write this:
group :test do
gem 'rspec-rails'
gem 'shoulda-matchers', require: false
gem 'factory_girl'
end
My rails_helper
require 'rspec/rails'
require 'shoulda/matchers'
My spec_helper
require 'rails_helper'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.include FactoryGirl::Syntax::Methods
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
# Choose a test framework:
with.test_framework :rspec
# Choose one or more libraries:
with.library :active_record
with.library :active_model
with.library :action_controller
end
end
And finally my test:
require 'spec_helper'
describe Person do
it {should validate_presence_of(:identifier)}
end
And I get nomethoderror
Failure/Error: it {should validate_presence_of(:identifier)}
NoMethodError:
undefined method `validate_presence_of' for #<RSpec::ExampleGroups::Person:0x007fe58d13ca20>
I simply don't get it. In other project the same way works. Here it doesn't. I have spent two days to fix this problem. Are there better alternatives of Shoulda Matchers in rails?
Sorry you're having trouble. You need to load Rails before you require shoulda-matchers. The gem will only make model matchers available if it can see that ActiveRecord is available; if not, then you won't get them.
It appears that you have rails_helper and spec_helper swapped. Typically in a fresh project with rspec-rails installed, rails_helper will load Rails and then require spec_helper. I would remove both files (or move them aside so you still have them) and then re-run rails g rspec:install to regenerate them. You'll still want to add the shoulda-matchers configuration block to rails_helper as you have done, but by that point ActiveRecord (and the rest of Rails) should be loaded.
Change your Gemfile to use two different groups for test like this:
group :test, :development do
gem 'rspec-rails'
gem 'factory_girl'
end
group :test do
gem 'shoulda-matchers', require: false
end
This used to be caused when shoulda would load with Test::Unit instead of RSpec, but I thought that was fixed.

Issue with Paperclip and Rspec: undefined method `has_attached_file'

I'm adding Rspec tests to a project that didn't have rspec before, or automated tests at all. It is running on a Windows 7 box. When I run rspec, it shows the error:
undefined method `has_attached_file'
The main issue is that I'm writing just a simple test for a model that is not using Paperclip at all. Paperclip is used on another model.
I've researched extensively, trying to include the gem in test environment but nothing seems to solve the issue.
Is there a way of skipping or forcing the inclussion of paperclip when I run the rspec tests?
My gemfile has, among other things, the following:
source 'http://rubygems.org'
ruby "1.9.2"
gem 'rails', '3.0.20'
...
gem "paperclip", :git => 'git://github.com/thoughtbot/paperclip.git'
gem 'aws-s3'
gem 'aws-sdk'
group :test, :development do
gem 'rspec-rails', '~> 2.14.0'
end
group :test do
gem 'sqlite3'
gem 'capybara', '2.0'
gem 'selenium-webdriver'
gem 'shoulda-matchers'
gem 'database_cleaner'
gem 'launchy', '2.2.0'
gem 'factory_girl_rails'
end
I run the rspec command:
bundle exec rake spec
I get the following error:
C:/Users/MAC/.pik/rubies/Ruby-192-p290/bin/ruby.exe -S rspec ./spec/models/filter_category_spec.rb ./spec/models/filter_spec.rb
C:/Users/MAC/.pik/rubies/Ruby-192-p290/lib/ruby/gems/1.9.1/gems/attr_encrypted-1.2.1/lib/attr_encrypted.rb:241:in `method_missing': undefined method `has_a
ttached_file' for #<Class:0x5278770> (NoMethodError)
from C:/Users/MAC/.pik/rubies/Ruby-192-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.0.20/lib/active_record/base.rb:1018:in `method_missing'
from C:/Users/MAC/.pik/rubies/Ruby-192-p290/lib/ruby/gems/1.9.1/gems/attr_encrypted-1.2.1/lib/attr_encrypted/adapters/active_record.rb:50:in `metho
d_missing_with_attr_encrypted'
....
from C:/Users/MAC/.pik/rubies/Ruby-192-p290/lib/ruby/gems/1.9.1/gems/railties-3.0.20/lib/rails/application.rb:77:in `method_missing'
from C:/Avity/DS Candidates Tracking System/ds-cts/config/environment.rb:5:in `<top (required)>'
from C:/Avity/DS Candidates Tracking System/ds-cts/spec/spec_helper.rb:3:in `require'
from C:/Avity/DS Candidates Tracking System/ds-cts/spec/spec_helper.rb:3:in `<top (required)>'
from C:/Avity/DS Candidates Tracking System/ds-cts/spec/models/filter_category_spec.rb:1:in `require'
My spec_helper file is:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
# 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|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
#Database cleaner
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
#Use chrome driver
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
Capybara.current_driver = :selenium_chrome
end
Any ideas of what should I do to make this work properly?
EDIT It seems the issue comes before loading spec_helper.rb
If I make changes on this file, like adding errors on purpose, nothing happens and the issue above keeps happening.
The only way I have to run the tests is by commenting the has_attached_file line on my model and adding the group option to the paperclip gem on my Gemfile, to avoid having it on test environment:
gem "paperclip", :git => 'git://github.com/thoughtbot/paperclip.git', :group=>[:development,:production]
Not sure how to solve this without skipping Paperclip from test env.
The problem seems to me to be with shoulda-matchers and paperclip
Add to your spec_helper.rb file
require "paperclip/matchers"
below where you are
require "capybara/rspec"
And add
config.include Paperclip::Shoulda::Matchers
below
RSpec.configure do |config|
Check out the shoulda-matchers documentation for paperclip
Hope this helps
I ran into this issue when trying to use Paperclip in a gem that has ActiveRecord, but not Rails. I was able to fix this for tests by adding a spec/support/paperclip.rb file with the following:
require 'paperclip/railtie'
RSpec.configure do |config|
# Bind paperclip to enable ActiveRecord #has_attached_file method
Paperclip::Railtie.insert
end
As also suggested, this is a good place to add config.include Paperclip::Shoulda::Matchers.
But I'm using Rails 4.2 and Rspec 3, so I think the order of things loaded is much different than yours.

uninitialized constant RSpec with spork

I'm trying to get spork working with a rails 2.3.18 app
Here is part of my gemfile showing Rspec versions:
gem "rails", "2.3.18"
gem "haml", "3.1.8"
gem "twitter", :git => "git://github.com/sferik/twitter.git", :tag => "v0.9.12"
gem 'rdoc', '~> 3.9.2'
group :test, :development do
gem "rspec", "1.3.1"
# gem 'rspec-mocks', '2.1.0'
# gem 'rspec-core', '2.1.0'
# gem 'rspec-expectations', '2.1.0'
gem "rspec-rails", "1.3.4"
# gem 'guard'
# gem 'guard-livereload'
# gem 'rb-fsevent', '~> 0.9'
# gem 'em-websocket'
gem 'spork'
end
Here is my spec_helper.rb
require 'rubygems'
require 'spork'
#require 'spork/ext/ruby-debug'
Spork.prefork do
# Loading more in this block will cause your tests to run faster. However,
# if you change any configuration or code from libraries loaded here, you'll
# need to restart spork for it take effect.
# This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] = 'test'
require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
require 'spec/autorun'
require 'spec/rails'
# Uncomment the next line to use webrat's matchers
#require 'webrat/integrations/rspec-rails'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
Spec::Runner.configure do |config|
# If you're not using ActiveRecord you should remove these
# lines, delete config/database.yml and disable :active_record
# in your config/boot.rb
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
# == Fixtures
#
# You can declare fixtures for each example_group like this:
# describe "...." do
# fixtures :table_a, :table_b
#
# Alternatively, if you prefer to declare them only once, you can
# do so right here. Just uncomment the next line and replace the fixture
# names with your fixtures.
#
# config.global_fixtures = :table_a, :table_b
#
# If you declare global fixtures, be aware that they will be declared
# for all of your examples, even those that don't use them.
#
# You can also declare which fixtures to use (for example fixtures for test/fixtures):
#
# config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
#
# == Mock Framework
#
# RSpec uses its own mocking framework by default. 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
#
# == Notes
#
# For more information take a look at Spec::Runner::Configuration and Spec::Runner
end
end
Spork.each_run do
# This code will be run each time you run your specs.
end
# --- Instructions ---
# Sort the contents of this file into a Spork.prefork and a Spork.each_run
# block.
#
# The Spork.prefork block is run only once when the spork server is started.
# You typically want to place most of your (slow) initializer code in here, in
# particular, require'ing any 3rd-party gems that you don't normally modify
# during development.
#
# The Spork.each_run block is run each time you run your specs. In case you
# need to load files that tend to change during development, require them here.
# With Rails, your application modules are loaded automatically, so sometimes
# this block can remain empty.
#
# Note: You can modify files loaded *from* the Spork.each_run block without
# restarting the spork server. However, this file itself will not be reloaded,
# so if you change any of the code inside the each_run block, you still need to
# restart the server. In general, if you have non-trivial code in this file,
# it's advisable to move it into a separate file so you can easily edit it
# without restarting spork. (For example, with RSpec, you could move
# non-trivial code into a file spec/support/my_helper.rb, making sure that the
# spec/support/* files are require'd from inside the each_run block.)
#
# Any code that is left outside the two blocks will be run during preforking
# *and* during each_run -- that's probably not what you want.
#
# These instructions should self-destruct in 10 seconds. If they don't, feel
# free to delete them.
Spork starts successfully.
When I run
./script/spec spec
the tests run successfully. However, if I pass the --drb option like so
./script/spec spec --drb
I get
Exception encountered: #<NameError: uninitialized constant RSpec>
had to use gem 'spork', '~> 0.8.0'

Rspec Undefined method 'should receive'

I'm trying to use rspec with mongoid but I'm running across this error:
undefined method `should_receive' for ShortenedUrl:Class
Here's my spec_helper.rb file:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/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
config.mock_with :rspec
# 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
config.before(:each) do
Mongoid.master.collections.each(&:drop)
end
end
And here's my test file:
require 'spec_helper'
describe UrlsController do
describe "POST make_short" do
context "when posting a valid url" do
# url = mock('ShortenedUrl')
url = Struct.new('ShortenedUrl')
ShortenedUrl.should_receive(:new).with(:url => 'http://example.com').and_return(url)
url.should_receive(:save!)
post :make_short, :url => 'http://example.com'
end
end
end
Finally, here's the Gemfile:
source 'http://rubygems.org'
gem 'rails', '3.0.3'
gem "mongoid", ">= 2.0.0.beta.19"
gem "rspec-rails", ">= 2.0.1", :group => [:development, :test]
gem "cucumber-rails", :group => :test
gem "capybara", :group => :test
From what I understand, I should get this error if I wasn't using the rspec mock, but in my case I'm using it. Any ideas?
Your test needs to be inside an example or it block (they're the same method):
it "when posting a valid url" do
# url = mock('ShortenedUrl')
url = Struct.new('ShortenedUrl')
ShortenedUrl.should_receive(:new).with(:url => 'http://example.com').and_return(url)
url.should_receive(:save!)
post :make_short, :url => 'http://example.com'
end
A context block is used for grouping similar examples.

Resources