rspec-rails+capybara NoMethodError:undefined method `create' - ruby-on-rails

I'm learning ruby on rails, but I have a problem that I couldn't solve by myself. Any one can help me?
when I run:bundle exec rspec spec/models/user_spec.rb, I got this error:
Failure/Error: #user = create(:user) NoMethodError:
undefined method `create' for #<RSpec::ExampleGroups::User::PropertiesShouldNotNil:0xb807450>
# ./spec/models/user_spec.rb:6:in `block (3 levels) in <top (required)>'
Gemfile:
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.0.0.rc2'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 2.3.0'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'alipay', '~> 0.10.0' #支付宝接口
gem 'capistrano-rails', :group => :development
gem 'capistrano-passenger', :group => :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
#gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'rspec-rails'
gem "capybara"
end
group :development do
gem 'web-console', group: :development
end
spec/rails_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
app/models/user.rb
app/models/user.rb
has_many :recipients
end
spec/models/user_spec.rb:
require 'rails_helper'
RSpec.describe User, type: :model do
context "properties should not nil" do
before do
#user = create(:user)
end
subject{ #user }
it { should respond_to(:name) }
it { should respond_to(:passwd) }
end
end

This error is because the create method you are trying to call is usually defined in the FactoryGirl class. FactoryGirl is a Ruby gem that lets you define custom factories to instantiate your application-specific models.
As you may need to integrate this gem in your Rails app, I suggest that you use the factory_girl_rails gem. Simply add the gem declaration into the :test group of your Gemfile, like as follows:
group :development, :test do
# Here go other gem declarations...
gem 'factory_girl_rails'
end
Once you have included this gem in your project, you'll need to define the factories for your models (in this case, your User model) in order to specify the way you want your test instances to be built or created. I recommend you read this basic documentation on how to define factories with FactoryGirl (I read this doc over and over).
In advance, I could tell you that the factories are usually defined under the spec/factories folder (in cases like this, that you are using RSpec) and have a common structure. In this case, your Userfactory would be defined in a file like spec/factories/user.rb and be like:
FactoryGirl.define do
factory :user do
# Here you assign values to the different attributes, like:
# username "username"
# password "pass"
# ...
end
end
I use the faker gem with FactoryGirl a lot, because it lets me create random values for names, telephone numbers, emails, etc in a way that are always different but make sense. Take a look at its documentation in case you are interested in it.
Hope these can help you solve your problem!

Related

Why am I getting unititialized constant in my Rspec model test?

I'm trying to create a test with Rspec in my rails application but I keep getting the following error.
uninitialized constant Build
# ./spec/models/build_spec.rb:3:in `<top (required)>'
No examples found.
I am running rails version 6.1.4.1. I also know that my model exists as I can create new objects that belong to that table in the ruby console.
here is my rspec file (spec/models/build_spec.rb)
require 'spec_helper'
RSpec.describe Build, type: :model do
it "Has a name"
it "is not valid without name"
it "is not valid with too short name"
it "is not valid with too long of a name"
end
here is my gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.7.4'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
gem 'rails', '~> 6.1.4', '>= 6.1.4.1'
# Use Puma as the app server
gem 'puma', '~> 5.0'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 5.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
gem 'will_paginate', '~> 3.3'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.4', require: false
group :development, :test do
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4.2'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 4.1.0'
# Display performance information such as SQL time and flame graphs for each request in your browser.
# Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md
gem 'rack-mini-profiler', '~> 2.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 3.26'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
gem 'rspec-rails', '>= 3.9.0'
end
group :production do
gem 'pg', '~> 1.1'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
spec_helper does not load the environment (this includes not loading the models). You could either require the model file explicitly in this spec or require rails_helper instead.
Check you have the right model inside the app/models/ directory.
spec/models/build_spec.rb
require 'rails_helper'
RSpec.describe Build, type: :model do
it { expect(described_class.new).to be_a() }
end
app/models/build.rb
class Build < ApplicationRecord
end
Hope this works for you.

getting cannot load such file -- cucumber-rails when running rspec

I am getting the following error when running RSpec
cannot load such file -- cucumber-rails
I am on Rails 4.2.7.1, rspec 3.5.4 and my cucumber tests successfully run when I do cucumber in app dir.
here's my rails_helper:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# 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
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
Gemfile
source 'https://rubygems.org'
# used for searching
gem 'rbing'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.7.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :test do
gem 'rspec-rails'
gem 'cucumber-rails', :require => true
gem 'database_cleaner'
gem 'vcr'
gem 'webmock'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
gem 'guard-spork'
gem 'guard-cucumber'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
change
gem 'cucumber-rails', :require => true
to
gem 'cucumber-rails', :require => false

how to impements gem shoulda in unit testing rails 4 without rspec?

how to implements gem shoulda in unit testing without respec?, this is my gemfile file :
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.4'
group :production do
# Use PostgreSQL as the database for Active Record on Heroku
gem 'pg'
end
group :development, :test do
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
gem "minitest"
gem 'byebug'
end
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
# gem 'byebug', group: [:development, :test]
gem 'devise'
gem 'shoulda'
gem 'omniauth-facebook'
gem 'omniauth-google-oauth2'
and this is my test_helper.rb file :
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
include Devise::TestHelpers
require 'minitest/autorun'
require 'shoulda/rails'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
this is my example model testing unit :
require 'test_helper'
class UserTest < ActiveSupport::TestCase
should validate_presence_of(:name)
should validate_presence_of(:last_name)
should validate_presence_of(:id_number)
should ensure_inclusion_of(:id_issuing_country).in_array(["Spain"])
should validate_presence_of(:birth_date)
should validate_presence_of(:email)
should validate_presence_of(:bank_account)
end
when i runing this in my console : bin/rake test test/models/user_test.rb
i get error like this :
LoadError: cannot load such file -- shoulda/rails
From a gem file for application I am working on
....
group :test do
# gem 'faker'
gem 'launchy'
gem 'relish'
gem 'selenium-webdriver', '~> 2.42.0'
gem 'capybara'
gem 'database_cleaner'
gem 'shoulda-matchers', '~>2.6.2'
gem 'shoulda'
end
....
hope this helps - Pierre

Why am I getting an error while using RSpec 3.0 with Capybara 2.3 in Rails 4.1?

I am new to Rails development. I am following Michael Hartl's video tutorials. However I am not able to run the tests using Capybara/RSpec. I am getting some errors. My setup is as follows:
I am using Ruby 2.0.0p353.
Rails - 4.1.1 and
RSpec - 3.0.1
Capybara - 2.3.0
Below is my GemFile.
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
ruby '2.0.0'
gem 'rails', '4.1.1'
gem 'bootstrap-sass'
gem 'bcrypt'
gem 'faker'
gem 'will_paginate'
gem 'bootstrap-will_paginate'
gem 'rails_12factor'
# Use sqlite3 as the database for Active Record
group :development, :test do
gem 'sqlite3'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'guard-spork'
gem 'childprocess'
gem 'spork'
end
#Gems used only for assets and not used in production enviornment by default
group :assets do
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
end
group :test do
gem 'capybara'
gem 'factory_girl_rails'
gem 'cucumber-rails'
gem 'database_cleaner'
#gem 'launchy'
#gem 'rb-fsevent'
#gem 'growl'
end
group :production do
gem 'pg'
end
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
Below is my spec/spec_helper.rb:
require 'capybara/rspec'
RSpec.configure do |config|
config.include Capybara::DSL
end
And, here is my spec. test - spec/features/static_pages_spec.rb
require 'spec_helper'
describe "Static pages" do
describe "Home page" do
it "should have the content 'Sample App'" do
visit '/static_pages/home'
page.should have_content('Sample App')
end
end
end
If I run the command rspec/featues/static_pages_spec.rb I get a long stack trace. It shows two main issues:
/usr/local/share/ruby/site_ruby/rubygems/core_ext/kernel_require.rb:73:
warning: loading in progress, **circular require considered harmful -
/home/MAC/.gem/ruby/gems/capybara-2.3.0/lib/capybara.rb**
and
An error occurred in an after hook
**ArgumentError: rack-test requires a rack application, but none was given**
occurred at /home/MAC/.gem/ruby/gems/capybara-2.3.0/lib/capybara/rack_test/driver.rb:16:in `initialize'
F
Failures:
1) Static pages Home page should have the content 'Sample App'
Failure/Error: visit '/static_pages/home'
ArgumentError:
**rack-test requires a rack application, but none was given**
# ./spec/features/static_pages_spec.rb:10:in `block (3 levels) in <top (required)>'
Finished in 0.00062 seconds (files took 0.58874 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/features/static_pages_spec.rb:8 # Static pages Home page should have the content 'Sample App'
I have tried googling for this issue. It seems Capybara 2.3.0 and RSpec 3.0.1 do not play nicely. However I haven't found any solution which solves the issue. Has anyone encountered and solved such an issue? Please let me know. Thanks in advance.
rspec-rails 3 no longer defaults to setting the spec type based on the location, so your spec isn't being setup as a feature spec
You can either tag the feature specs individually or add
config.infer_spec_type_from_file_location!
To your spec helper to restore the old behaviour

Rspec view undefined method stub_model

i'm trying to find out what is wrong with this code. Namely it cannot find method 'stub_model'. Tried to look for solution for this but everywhere i look my files seems to be good. Please take a look on it maybe i just can't see a simple mistake. Thanks a lot :)
Book model is created in db.
My view spec (spec/view/books_spec.rb) looks like this:
require 'rails_helper'
describe 'books/new' do
it 'displays the book form' do
book = stub_model(Book)
assign(:book, book)
render
expect(rendered).to have_selector("form label[for *= 'Title']")
expect(rendered).to have_selector("form label[for *= 'Author']")
expect(rendered).to have_selector("form label[for *= 'Cover Photo']")
expect(rendered).to have_button "Add Book"
end
end
and the error is following:
1) books/new displays the book form
Failure/Error: book = stub_model(Book)
NoMethodError:
undefined method `stub_model' for #<RSpec::ExampleGroups::BooksNew:0x00000103e61870>
# ./spec/views/books_spec.rb:6:in `block (2 levels) in <top (required)>'
My rails_helper.rb looks like:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
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. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# 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
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
and my Gemfile.rb:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.2.rc1'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
group :test do
gem 'cucumber-rails', :require => false
gem 'database_cleaner'
end
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
end
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
What is your rspec-rails version?
According to the Changelog and this Commit mock_model and stub_model are removed since version 3.0.0 of rspec-rails.
rspec mocks are externalized in an another gem rspec-activemodel-mocks . You should include it in your Gemfile and try it.
Hope it helps
this should be a comment to ahnbizcad's comment, but I lack the reputation to do it properly.
It should be fixed by adding
require 'rspec/active_model/mocks'
to spec_helper.rb

Resources