NoMethodError: undefined method `users' within a setup - ruby-on-rails

maybe is a dumb question, but I am having an issue when I am trying to run a test on Ruby, this is the error:
Error: UsersLoginTest#test_login_with_valid_information:
NoMethodError: undefined method `User' for #UsersLoginTest:0x0000555ef3ec15b0 Did you mean? super
test/integration/users_login_test.rb:6:in `setup'
I tried to fix the fixture .yml but I am not sure that the problem is there anymore.
This is my users.yml
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
this is my users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "login with valid information" do
get login_path
post login_path, params: { session: { email: #user.email,
password: 'password' } }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
end
and this is my test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class UserTest < ActiveSupport::TestCase
fixtures :all
include ApplicationHelper
setup do
#user = User.new(name: "Example User", email: "user#example.com",
password: "foobar", password_confirmation: "foobar")
end
test "should be valid" do
assert #user.valid?
end
end
where could be the problem? thank you very much for your help
New Attachments
irb(main):002:0> User.column_names
=> ["id", "name", "email", "created_at", "updated_at", "password_digest"]
I tried changing password_digest: 123456, but it throws the same error.
I tried changing to password: test_password, and this comes up:
UserTest#test_should_be_valid:
ActiveRecord::Fixture::FixtureError: table "users" has no columns
named "password".
Also I am attaching my gem file, where the only file I intentional used to authentication was gem 'bcrypt' I think:
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.3'
gem 'rails', '6.0.1'
gem 'autoprefixer-rails', '9.6.1.1'
gem 'uglifier', '3.2.0'
gem 'coffee-rails', '5.0.0'
gem 'jquery-rails', '4.3.5'
gem 'mini_magick', '4.9.5'
gem 'will_paginate', '3.2.1'
gem 'bootstrap-will_paginate', '1.0.0'
gem 'bootstrap-sass', '3.4.1'
gem 'puma', '4.3.1'
gem 'font-awesome-rails', '4.7.0.5'
gem 'sass-rails', '6'
gem 'webpacker', '4.0'
gem 'turbolinks', '5'
gem 'jbuilder', '2.9.1'
gem 'rubocop', '0.77.0'
gem 'bootsnap', '1.4.2', require: false
gem 'rails-controller-testing'
gem 'bcrypt', '3.1.12'
group :development, :test do
gem 'sqlite3', '1.4.1'
gem 'byebug', platforms: %i[mri mingw x64_mingw]
end
group :development do
gem 'web-console', '3.3.0'
gem 'listen', '3.2.0'
gem 'spring'
gem 'spring-watcher-listen', '2.0.0'
end
group :test do
gem 'capybara', '3.28.0'
gem 'selenium-webdriver', '3.142.4'
gem 'webdrivers', '4.1.2'
end
group :production do
gem 'pg', '0.20.0'
# gem 'fog', '1.42'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
And just in case I created a repository: https://github.com/cochabambinoski/Share-Exercise

Ok, your problem is you set up test_helper.rb as a test itself and that is causing you problems. Your file should look like:
#test_helper.rb
ENV['RAILS_ENV'] = 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase #you were creating a new class in your code
fixtures :all
include ApplicationHelper
end
That's it, all I had to do after cloning your repo was to bundle install, and do a rake db:create and rake db:test:prepare. Now the test passes. Don't forget to change your fixture back to:
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
Big lesson here is test_helper.rb is a place for some configuration and settings, not the place to put tests.

Related

Ruby on Rails Tutorial : Integration test error

I'm just getting started with Ruby on Rails and I already feel like an idiot being stuck on something that seems so simple.
I'm stuck on Chapter 7.3.4 of Michael Hartl's Ruby on Rails tutorial. I'm doing an Integration Test on a user signup to check for invalid form submission.
I've thoroughly followed the tutorial so far and have been able to grasp every concept or error I ran into, but this one got me stuck. Upon trying Rails t in the Console (Ubuntu), I'm getting the following error :
ERROR["test_invalid_signup_information", #<Minitest::Reporters::Suite:0x000055b0dec5f190 #name="UsersSignupTest">, 1.8036143100000004]
test_invalid_signup_information#UsersSignupTest (1.80s)
ArgumentError: ArgumentError: wrong number of arguments (given 2, expected 1)
test/integration/users_signup_test.rb:8:in `block (2 levels) in <class:UsersSignupTest>'
test/integration/users_signup_test.rb:7:in `block in <class:UsersSignupTest>'
19/19: [=================================] 100% Time: 00:00:01, Time: 00:00:01
Finished in 1.84116s
19 tests, 38 assertions, 0 failures, 1 errors, 0 skips
Here is the test file itself, where the error comes from :
require "test_helper"
class UsersSignupTest < ActionDispatch::IntegrationTest
test "invalid signup information" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user#invalid",
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
end
Here is the User controller file :
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
# Handle a successful save.
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
And here is my Gemfile :
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '3.0.0'
gem 'rails', '6.1.0'
gem 'bcrypt', '3.1.13'
gem 'bootstrap-sass', '3.4.1'
gem 'puma', '5.0.4'
gem 'sass-rails', '6.0.0'
gem 'webpacker', '4.2.2'
gem 'turbolinks', '5.2.1'
gem 'jbuilder', '2.10.0'
gem 'rexml'
gem 'bootsnap', '1.4.6', require: false
group :development, :test do
gem 'sqlite3', '1.4.2'
gem 'byebug', '11.1.3', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
gem 'web-console', '4.1.0'
gem 'listen', '3.4.1'
gem 'spring', '2.1.1'
gem 'spring-watcher-listen', '2.0.1'
end
group :test do
gem 'capybara', '3.32.2'
gem 'selenium-webdriver', '3.142.7'
gem 'webdrivers', '4.3.0'
gem 'rails-controller-testing', '1.0.4'
gem 'minitest', '5.11.3'
gem 'minitest-reporters', '1.3.8'
gem 'guard', '2.16.2'
gem 'guard-minitest', '2.4.6'
gem 'pry'
end
group :production do
gem 'pg', '1.2.3'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
# Uncomment the following line if you're running Rails
# on a native Windows system:
# gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
I've searched for similar threads and actually found this on StackOverflow :
Chapter 7 Errors, Ruby on Rails tutorial
I do think it's the syntax of the test that must be changed, and I've tried the solution suggested on there, but the test still fails tells me about a wrong number of arguments. It must be pretty simple, although I'm just not seeing it...
Thank you guys in advance for your time and help !
I was receiving and was baffled by the same error. It says that on the line with the TestCase method post I was passing two arguments, while it expected just one. I'm not sure why, since the documentation for that method indicates that it does indeed take two arguments - an action and an args hash.
Anyway, I decided to just follow the logic of the error and write it so that it's only one argument being passed to post - I removed the comma between users_path and params:
assert_no_difference 'User.count' do
post users_path params: { user: { name: "", email: "user#invalid", password: "foo", password_confirmation: "bar" } }
end
I have no idea why that works, especially as it seems to be wrong according to the documentation. But the test now passes without errors.

Setting up factory girl in Rails 5. Docs seem to leave out an important step

What am I doing wrong? It seems like nowhere in the docs does it say to put:
require 'factory_girl_rails'
require 'support/factory_girl'
in your rails_helper.
This is my setup without the two lines:
Gemfile:
source 'https://rubygems.org'
gem 'rails', '>= 5.0.0.beta3', '< 5.1'
gem 'sqlite3'
gem 'puma'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks', '~> 5.x'
gem 'jbuilder', '~> 2.0'
gem 'carrierwave'
gem 'carrierwave_direct'
gem "mini_magick"
group :development, :test do
gem 'pry'
gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
gem 'database_cleaner', '~> 1.5', '>= 1.5.1'
end
group :development do
gem 'web-console', '~> 3.0'
gem 'listen', '~> 3.0.5'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
User model:
class User < ApplicationRecord
has_many :images
end
Factories.rb file inside spec:
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "jeff#{n}" }
after(:build) do |user, eval|
user.images << build(:image)
end
end
factory :image do
avatar File.open(File.join(Rails.root, '/spec/support/images/blueapron.jpg'))
end
end
This is my spec/models/user_spec.rb:
describe User do
before(:each) do
#user = create(:user)
end
describe "images" do
it "should have multiple images" do
require 'pry' ; binding.pry
#user.images.create({document_file:File.open(File.join(Rails.root, '/spec/fixtures/files/image.png'))})
#user.images.create({document_file:File.open(File.join(Rails.root, '/spec/fixtures/files/image.png'))})
#user.images.length.should eq(3)
end
end
end
When I run my tests:
Failures:
1) User images should have multiple images
Failure/Error: #user = create(:user)
NoMethodError:
undefined method `create' for #<RSpec::ExampleGroups::User::Images:0x007fea80756f08>
# ./spec/models/user_spec.rb:4:in `block (2 levels) in <top (required)>'
AFter I include those two lines back into my rails_helper:
# 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'
require 'factory_girl_rails'
require 'support/factory_girl'
All of a sudden it works now:
before(:each) do
4: #user = create(:user)
5: end
6: describe "images" do
7: it "should have multiple images" do
=> 8: require 'pry' ; binding.pry
9:
10: #user.images.create({document_file:File.open(File.join(Rails.root, '/spec/fixtures/files/image.png'))})
11: #user.images.create({document_file:File.open(File.join(Rails.root, '/spec/fixtures/files/image.png'))})
12:
13: #user.images.length.should eq(3)
[1] pry(#<RSpec::ExampleGroups::User::Images>)> #user
=> #<User:0x007f86e86cbcd8 id: 1, name: "jeff2", created_at: Thu, 17 Mar 2016 04:39:42 UTC +00:00, updated_at: Thu, 17 Mar 2016 04:39:42 UTC +00:00>
I don't even remember where I found those two lines. Is it in the docs anywhere to include those lines?
In your factory, you use build:
after(:build) do |user, eval|
user.images << build(:image)
end
And in your specs you use create:
describe User do
before(:each) do
#user = create(:user)
end
You have to use same hook, I recommend you to:
Use build instead of create and save record in your before(:each) block
Include another hook for after(:create) in your factory and create (not build) an image

undefined method `authenticate' on Devise + Rspec + render_view

I have Rails 4.2.5 and rspec 3.4.1
When I add render_views some first controllers test are failed.
I use render_views because I don't know any methods to watch what happens on a page.
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.5'
gem 'sqlite3'
gem 'haml-rails', '~> 0.9'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'twitter-bootstrap-rails'
gem 'less-rails'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'rspec-rails', '~> 3.0'
gem 'cucumber-rails', :require => false
gem 'database_cleaner'
gem 'factory_girl_rails'
gem 'shoulda-matchers'
gem 'capybara'
gem 'capybara-screenshot'
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
gem 'spring'
end
gem 'devise'
gem 'cancan'
gem "role_model"
gem 'paperclip', '~> 4.3'
gem 'jquery-fileupload-rails'
gem 'stringex'
gem 'will_paginate'
gem 'russian', '~> 0.6.0'
spec/controllers/users_controller_spec.rb
RSpec.describe UsersController, type: :controller do
render_views
let(:valid_attributes) {
{email: "admin#example.com",
password: "password",
password_confirmation: "password"}
}
let(:invalid_attributes) {
}
let(:valid_session) { {} }
describe "GET #index" do
it "says 'Users'" do
get :index
end
end
...
end
spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'devise'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
rspec spec/controllers/page_controller_spec.rb
PageController
GET #index
returns http success (FAILED - 1)
Failures:
1) PageController GET #index returns http success
Failure/Error: - if user_signed_in?
ActionView::Template::Error:
undefined method `authenticate' for nil:NilClass
# /home/ilp/.rvm/gems/ruby-2.1.4/gems/devise-3.5.3/lib/devise/controllers/helpers.rb:124:in `current_user'
# /home/ilp/.rvm/gems/ruby-2.1.4/gems/devise-3.5.3/lib/devise/controllers/helpers.rb:120:in `user_signed_in?'
# ./app/views/layouts/main.html.haml:36:in `_app_views_layouts_main_html_haml___2814915178728912122_59040000'
# ./spec/controllers/page_controller_spec.rb:11:in `block (3 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# NoMethodError:
# undefined method `authenticate' for nil:NilClass
# /home/ilp/.rvm/gems/ruby-2.1.4/gems/devise-3.5.3/lib/devise/controllers/helpers.rb:124:in `current_user'
Finished in 0.26407 seconds (files took 1.9 seconds to load)
1 example, 1 failure
app/controllers/page_controller.rb
class PageController < ApplicationController
def index
end
end
If I call sign_in or sign_our methods tests are success.
You need to call the sign_in method before rendering as it check the current_user object and calls the authenticate! method on current_user object which is nil so throwing error!
Do it like this
before do
sign_in_user
end
this will set the current_user object.

uninitialized constant TestFactories (NameError)

I am a beginner in Ruby on Rails and I am writing a "User sign in" spec for a wiki project, and I am getting the following error:
uninitialized constant TestFactories (NameError)
This is my sign_in_spec.rb
require 'rails_helper'
describe "Sign in flow" do
include TestFactories
before do
#user = authenticated_user
end
describe "successful" do
it "redirects user to the wikis index" do
user = authenticated_user
visit root_path
end
end
end
This is my test_factories.rb file:
module TestFactories
def authenticated_user(options={})
user_options = { email: "email#{rand}#fake.com", password: 'password' }.merge(options)
user = User.new(user_options)
user.skip_confirmation!
user.save
user
end
end
This is my Gemfile:
source 'https://rubygems.org'
gem 'rails'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'bootstrap-sass', '~> 3.2.0'
gem 'autoprefixer-rails'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# Testing
group :develpment, :test do
gem 'rspec-rails'
gem 'capybara'
gem 'database_cleaner'
gem 'factory_girl_rails', '~> 4.0'
gem 'pry-rails'
end
# Databases
# Developemnt
gem 'sqlite3'
or you can do something like this in sepc helper
RSpec.configure do |config|
config.include TestFactories
end

Rspec Load Error in Ruby

I am working through Hartl's Ruby on Rails tutorial and am trying to test for user signups with invalid information and am getting a "Load Error" when running rspec. I am unsure how to fix this error, as I have updated my gem files.
$ bundle exec rspec spec/requests/user_pages_spec.rb \ > -e "signup with invalid information"
then I get this message:
/Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load': cannot load such file -- /Users/kelvinyu/rails_projects/sample_app/signup with invalid information (LoadError)
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `block in load_spec_files'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `each'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load_spec_files'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in `run'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:77:in `rescue in run'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:73:in `run'
from /Users/kelvinyu/.rvm/gems/ruby-2.0.0-p247#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'
Here is my spec/requests/user_pages_spec.rb:
require 'spec_helper'
describe "UserPages" do
subject { page }
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }
it { should have_content(user.name) }
it { should have_title(user.name) }
end
describe "signup page" do
before { visit signup_path }
# Run the generator again with the --webrat flag if you want to use webrat methods/matchers
it { should have_content('Sign up') }
it { should have_title(full_title('Sign up')) }
end
describe "signup" do
before { visit signup_path }
let(:submit) { "Create my account" }
describe "with invalid information" do
it "should not create a user" do
expect { click_button submit }.not_to change(User, :count)
end
end
describe "with valid information" do
before do
fill_in "Name", with: "Example User"
fill_in "Email", with: "user#example.com"
fill_in "Password", with: "foobar"
fill_in "Confirmation", with: "foobar"
end
it "should create a user" do
expect { click_button submit }.to change(User, :count).by(1)
end
end
end
end
And my Gemfile:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.1.2'
gem 'will_paginate', '3.0.4'
gem 'bootstrap-will_paginate', '0.0.9'
group :development, :test do
gem 'sqlite3', '1.3.7'
gem 'rspec-rails', '2.13.1'
# The following optional lines are part of the advanced setup.
gem 'guard-rspec', '2.5.0'
gem 'spork-rails', github: 'sporkrb/spork-rails'
gem 'guard-spork', '1.5.0'
gem 'childprocess', '0.3.6'
end
group :test do
gem 'selenium-webdriver', '2.0.0'
gem 'capybara', '2.1.0'
gem 'factory_girl_rails', '4.2.1'
gem 'cucumber-rails', '1.3.0', :require => false
gem 'database_cleaner', github: 'bmabey/database_cleaner'
# Uncomment this line on OS X.
# gem 'growl', '1.0.3'
# Uncomment these lines on Linux.
# gem 'libnotify', '0.8.0'
# Uncomment these lines on Windows.
# gem 'rb-notifu', '0.0.4'
# gem 'win32console', '1.3.2'
end
gem 'sass-rails', '4.0.0'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
Am I missing any other information? What is the appropriate step to fix this error?
EDIT:
Spec helper here:
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the StaticPagesHelper. For example:
# describe StaticPagesHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
#describe StaticPagesHelper do
# pending "add some examples to (or delete) #{__FILE__}"
#end
I notice that it is empty, however, the tutorial's steps did not require any changes.
Your error says the framework cannot load the file "/Users/kelvinyu/rails_projects/sample_app/signup with invalid information" which clearly isn't a file—the file is "spec/requests/user_pages_spec.rb". Try having everything in one line—without the \ > (this slash angle bracket only means that there, maybe, was a line break when Michael Hartl was typing up the tutorial.
Also, look to using describe and context interchangeably. This would make you write clearer specs. There is no magic to it. The sourcecode for RSpec shows that context is just another name for describe. But when you write specs with both, the meanings are clearer.

Resources