Rspec unit test case getting failed - ruby-on-rails

I have written some Rspec test cases in my spec/models/season_spec.rb file. They are as:-
require 'spec_helper'
describe Season do
it 'should not be without name' do
Season.new(:name=>nil,:number_of_weeks=>'3',:start_date=>'2012-02-07',:user_id=>'113').should_not be_valid
end
it 'should not be without number of weeks' do
Season.new(:name=>'Apurva',:number_of_weeks=>nil,:start_date=>'2012-02-07',:user_id=>'113').should_not be_valid
end
it 'should not be without start_date' do
Season.new(:name=>'Apurva',:number_of_weeks=>'3',:start_date=>nil,:user_id=>'113').should_not be_valid
end
it 'should not be without user_id' do
Season.new(:name=>'Apurva',:number_of_weeks=>'3',:start_date=>'2012-02-07',:user_id=>nil).should_not be_valid
end
it 'should be with valid attributes' do
Season.new(:name=>'Apurva',:number_of_weeks=>'3',:start_date=>'2012-02-07',:user_id=>'113').should be_valid
end
end
And in my model i have validated these fields as :-
class Season < ActiveRecord::Base
validates_presence_of :name,:number_of_weeks,:start_date,:user_id
end
But still the test cases are failed. And it is giving me following output:-
/usr/lib/ruby/gems/1.8/gems/bundler-1.0.21/lib/bundler/runtime.rb:138: warning: Insecure world writable dir /usr/lib/ruby/gems/1.8 in PATH, mode 040777
FFFFF
Failures:
/usr/lib/ruby/gems/1.8/gems/rspec-core-2.8.0/lib/rspec/core/formatters/base_text_formatter.rb:165:in `pending_fixed?': undefined method `pending_fixed?' for #<ActiveRecord::StatementInvalid:0xb6cd03c8> (NoMethodError)
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.8.0/lib/rspec/core/formatters/base_text_formatter.rb:19:in `dump_failures'
from /usr/lib/ruby/gems/1.8/bundler/gems/rails-27357a6965eb/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:473:in `each_with_index'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.8.0/lib/rspec/core/formatters/base_text_formatter.rb:17:in `each'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.8.0/lib/rspec/core/formatters/base_text_formatter.rb:17:in `each_with_index'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.8.0/lib/rspec/core/formatters/base_text_formatter.rb:17:in `dump_failures'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:75:in `send'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:75:in `notify'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:74:in `each'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:74:in `notify'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:23:in `conclude'
from /usr/lib/ruby/vendor_ruby/rspec/core/reporter.rb:14:in `report'
from /usr/lib/ruby/vendor_ruby/rspec/core/command_line.rb:24:in `run'
from /usr/lib/ruby/vendor_ruby/rspec/core/runner.rb:55:in `run_in_process'
from /usr/lib/ruby/vendor_ruby/rspec/core/runner.rb:46:in `run'
from /usr/lib/ruby/vendor_ruby/rspec/core/runner.rb:10:in `autorun'
from /usr/bin/rspec:4

First, there is a typo in the 'should not be without name' spec. Please check if this is just a typo while typing the quetion here, or in your code.
Second, these tests are pointless since that code is already tested here.

Related

Rspec error uninitialized constant

I've got a recruitment task to do from a company, that concerns Rspec. After cloning their repo on which I have to work I immediately run on some errors. I am completely new in Rspec or testing in general actually, I would like to improve, but this error is something I can't find a solution to.
spec/validators/title_brackets_validator_spec.rb
require "rails_helper"
describe TitleBracketsValidator do
subject { Validatable.new(title: title) }
shared_examples "has valid title" do
it "should be valid" do
expect(subject).to be_valid
end
end
context "with curly brackets" do
let(:title) { "The Fellowship of the Ring {Peter Jackson}" }
it_behaves_like "has valid title"
end
[ more not important 'contexts'...]
end
class Validatable
include ActiveModel::Validations
validates_with TitleBracketsValidator
attr_accessor :title
def initialize(title:)
#title = title
end
end
and while running bundle exec rspec I get an error:
An error occurred while loading ./spec/validators/title_brackets_validator_spec.rb.
Failure/Error:
describe TitleBracketsValidator do
subject { Validatable.new(title: title) }
shared_examples "has valid title" do
it "should be valid" do
expect(subject).to be_valid
end
end
shared_examples "has invalid title" do
NameError:
uninitialized constant TitleBracketsValidator
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/active_support.rb:53:in `block in load_missing_constant'
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/active_support.rb:8:in `without_bootsnap_cache'
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/active_support.rb:53:in `rescue in load_missing_constant'
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/active_support.rb:43:in `load_missing_constant'
# ./spec/validators/title_brackets_validator_spec.rb:3:in `<top (required)>'
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
# ------------------
# --- Caused by: ---
# NameError:
# uninitialized constant TitleBracketsValidator
# /var/lib/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/active_support.rb:43:in `load_missing_constant'
Finished in 0.00045 seconds (files took 1.57 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
Coverage report generated for RSpec to /home/maciej/Templates/task_app/coverage. 0 / 108 LOC (0.0%) covered.
Read your assignment carefully - maybe one of your tasks is to add the file and implement the class TitleBracketsValidator so it passes all the provided tests?
I'd search for the class in your sources. If not there - maybe you should create one. If it's there - then it's a loading issue. require it in your specs and notify the recruiter that you fixed a possible bug (for extra points maybe)

Rspec - PG::UndefinedTable: ERROR: relation "application" does not exist

I'm trying to start building out and running my rspec tests using bin rails\test. They used to work a while ago, but now when I run them i'm getting the error below for every single test.
Error:
VenueTest#test_should_not_save_venue_without_name:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "application" does not exist
LINE 1: DELETE FROM "application"
^
: DELETE FROM "application"
Finished in 0.382377s, 41.8435 runs/s, 0.0000 assertions/s.
16 runs, 0 assertions, 0 failures, 16 errors, 0 skips
I've barely written any tests, so it's just the pre-rolled ones that are now failing.
I've tried running the migrations (which run fine) and the test db is definitely created. I've also tried:
rake db:test:prepare
rake db:test:load
but still getting the same error. I also don't have a model named 'application', so no idea why it's trying to delete from "application"?
I'm guessing this is some sort of weird config thing that i've messed up somewhere along the way, but have no idea what it could be!
All tests are failing, but the tests in question are:
Home_Controller_test.rb
require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get home_index_url
assert_response :success
end
end
offers_controller_test.rb
require 'test_helper'
class OffersControllerTest < ActionDispatch::IntegrationTest
setup do
#offer = offers(:one)
end
test "should get index" do
get offers_url
assert_response :success
end
test "should get new" do
get new_offer_url
assert_response :success
end
test "should create offer" do
assert_difference('Offer.count') do
post offers_url, params: { offer: { desc: #offer.desc, end: #offer.end, offertype: #offer.offertype, start: #offer.start } }
end
assert_redirected_to offer_url(Offer.last)
end
test "should show offer" do
get offer_url(#offer)
assert_response :success
end
test "should get edit" do
get edit_offer_url(#offer)
assert_response :success
end
test "should update offer" do
patch offer_url(#offer), params: { offer: { desc: #offer.desc, end: #offer.end, offertype: #offer.offertype, start: #offer.start } }
assert_redirected_to offer_url(#offer)
end
test "should destroy offer" do
assert_difference('Offer.count', -1) do
delete offer_url(#offer)
end
assert_redirected_to offers_url
end
end
venues_controller_test.rb
require 'test_helper'
class VenuesControllerTest < ActionDispatch::IntegrationTest
setup do
#venue = venues(:one)
end
test "should get index" do
get venues_url
assert_response :success
end
test "should get new" do
get new_venue_url
assert_response :success
end
test "should create venue" do
assert_difference('Venue.count') do
post venues_url, params: { venue: { desc: #venue.desc, exists: #venue.exists, latitude: #venue.latitude, longitude: #venue.longitude, name: #venue.name, region: #venue.region, vtype: #venue.vtype } }
end
assert_redirected_to venue_url(Venue.last)
end
test "should show venue" do
get venue_url(#venue)
assert_response :success
end
test "should get edit" do
get edit_venue_url(#venue)
assert_response :success
end
test "should update venue" do
patch venue_url(#venue), params: { venue: { desc: #venue.desc, exists: #venue.exists, latitude: #venue.latitude, longitude: #venue.longitude, name: #venue.name, region: #venue.region, vtype: #venue.vtype } }
assert_redirected_to venue_url(#venue)
end
test "should destroy venue" do
assert_difference('Venue.count', -1) do
delete venue_url(#venue)
end
assert_redirected_to venues_url
end
end
EDIT
Stacktrace below as requested:
bin/rails test test/controllers/offers_controller_test.rb:18
E
Error:
VenueTest#test_should_not_save_venue_without_name:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "application" does not exist
LINE 1: DELETE FROM "application"
^
: DELETE FROM "application"
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:614:in `async_exec'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:614:in `block (2 levels) in exec_no_cache'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:46:in `block in permit_concurrent_loads'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activesupport-5.1.4/lib/active_support/concurrency/share_lock.rb:185:in `yield_shares'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activesupport-5.1.4/lib/active_support/dependencies/interlock.rb:45:in `permit_concurrent_loads'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:613:in `block in exec_no_cache'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract_adapter.rb:612:in `block (2 levels) in log'
/Users/James/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract_adapter.rb:611:in `block in log'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activesupport-5.1.4/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract_adapter.rb:603:in `log'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:612:in `exec_no_cache'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:599:in `execute_and_clear'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:92:in `exec_delete'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/database_statements.rb:145:in `delete'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/query_cache.rb:17:in `delete'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:546:in `block (4 levels) in create_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:544:in `each_key'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:544:in `block (3 levels) in create_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:540:in `each'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:540:in `block (2 levels) in create_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `block in transaction'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/transaction.rb:194:in `block in within_new_transaction'
/Users/James/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/transaction.rb:191:in `within_new_transaction'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/abstract/database_statements.rb:235:in `transaction'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:538:in `block in create_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/connection_adapters/postgresql/referential_integrity.rb:22:in `disable_referential_integrity'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:523:in `create_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:1028:in `load_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:965:in `setup_fixtures'
/Users/James/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.4/lib/active_record/fixtures.rb:851:in `before_setup'
EDIT - added Venue_test.rb
require 'test_helper'
class VenueTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "should not save venue without name" do
venue = Venue.new
assert_not venue.save, "Saved the venue without a title"
end
end
Running below command fixed this error for me:
RAILS_ENV=test rake db:test:prepare
Thanks #guy-yogev
Just in case anyone else is seeing this issue, there were extra files in the test/fixtures folder (maybe created by the generator). #dskecse identified the issue.
Once these are removed scripts run fine.

Rails and rspec. uninitialized constant Errors

I have a rails App. I have this file app/errors/status.rb
I try to pass the test but is not not working.
module Errors
class Status
def initialize status
#status = status
end
def default_message
"Error in the server status: #{status}"
end
private
attr_reader :status
end
end
And the test on spec/errors/status_spec.rb:
require 'rails_helper'
describe Errors::Status do
let(:status) { double 'status' }
subject { described_class.new status }
describe 'default_message' do
it 'returns the default message' do
expect(subject.call).to eq( "Error in the server status: #{status}")
end
end
end
And it keeps throwing this error:
/Users/gerardmorera/bet_play/spec/errors/status_spec.rb:3:in `<top (required)>': uninitialized constant Errors (NameError)
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `load'
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `block in load_spec_files'
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `each'
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `load_spec_files'
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:102:in `setup'
from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:88:in `run'
That’s because of how ActiveSupport’s auto-loading works and the way in which Rails sets up the $LOAD_PATH. Autoload sees Errors::Status and expects to find it at errors/status somewhere via require, but it doesn’t because app/errors is in the $LOAD_PATH, so you would require your file with just require 'errors'.
You can fix this by moving app/errors/status.rb to a location ActiveSupport’s auto-loading expects (e.g. app/<something>/errors/status.rb). You can puts $LOAD_ATH to see all the possible locations (note that Rails will add all directories in app/ to the $LOAD_PATH).

Rails test spec will not build my user model

There are so many moving parts to Rails testing that it's difficult to debug a failing test sometimes.
As a case in point, I am attempting to use zeus, guard, rspec, capybara, Poltergeist, PhantomJS, and FactoryGirl to simply build a User factory.
I am met with the following error message:
spec/models/user.rb
require 'spec_helper'
describe User do
describe 'Factories' do
it { expect(build :user).to be_valid }
end
end
spec/factories/users.rb
FactoryGirl.define do
factory :user do
sequence(:email) { |n| Forgery(:internet).email_address }
sequence(:company) { |n| Forgery(:name).company_name }
password "password"
password_confirmation "password"
end
end
Now I have a request spec that fails on the following line, which is the setup at the beginning:
let!(:user) { login_user }
The failure is this:
Failure/Error: let!(:user) { login_user }
NoMethodError:
undefined method `last_logged_in_at=' for #<User:0x007fe60aca95e8>
# ./app/models/user.rb:136:in `set_login_time'
# ./app/controllers/sessions_controller.rb:24:in `create'
# ./spec/support/login_macros.rb:7:in `login_user'
# ./spec/requests/app_integration_spec.rb:5:in `block (2 levels) in <top (required)>'
# ./custom_plan.rb:12:in `spec'
# -e:1:in `<main>'
So the problem appears to be that since User is not a real object, there is no such attribute as last_logged_in_at. So I should have to mock that somewhere. I tried putting this inside the factory code:
before(:build) do |u|
u.stub!(:read_attribute).with(:last_logged_in_at).and_return(Time.now)
end
The error remains the same. The test simply can not find this attribute. Keep in mind this code works perfectly in the browser. I am out of my league. Where am I going wrong?
Is your test db schema up-to-date?
rake db:test:prepare

RSPEC failed with email formats

I have been browsing the Rails tutorial with putting together the user account and running tests on it for the project I am working on.
Failures:
1) when email format is invalid should be invalid
Failure/Error: #user.email = invalid_address
NoMethodError:
undefined method `email=' for nil:NilClass
# ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:70:in `each'
# ./spec/models/user_spec.rb:70:in `block (2 levels) in <top (required)>'
2) when email format is valid should be valid
Failure/Error: #user.email = valid_address
NoMethodError:
undefined method `email=' for nil:NilClass
# ./spec/models/user_spec.rb:81:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:80:in `each'
# ./spec/models/user_spec.rb:80:in `block (2 levels) in <top (required)>'
Finished in 0.527 seconds
9 examples, 2 failures
Failed examples:
rspec ./spec/models/user_spec.rb:67 # when email format is invalid should be invalid
rspec ./spec/models/user_spec.rb:78 # when email format is valid should be valid
I have no clue what the problem is. I see what it says, but I even C&P the code from the tutorial to double check what I did to ensure everything was type properly.
Here's the user_spec file.
https://gist.github.com/pwz2k/4770845
Here's the user.rb file.
https://gist.github.com/pwz2k/4770854
The fails did not appear until I added the email validation.
Make sure that you're creating #user before you start testing it.. do you have these lines in your User test? (rails tutorial listing 6.16)
before do
#user = User.new(name: "Example User", email: "user#example.com")
end
The error is very clear!. You're setting email to nil class. Which means you're supposed to set the email to a user which we say
#user.email = "something"
The error is complaining there is no user, and there won't be any email for user.
To make is work here is an example code which will help you to fix this issue.
describe "validations" do
before(:each) do
#user = User.new(name: "gates", email: "somename#gmail.com")
end
it "should be invalid" do
invalid_emails = %w{gs#gmail p.com name.gmail.com foo.ymail}
invalid_emails.each do |invalid_email|
#user.email = invalid_email
expect(#user.email).to_not be_valid
end
end
it "should be valid" do
#user.name = "somename"
valid_emails = %w{user#foo.COM A_US-ER#f.b.org frst.lst#foo.jp
a+b#baz.cn}
valid_emails.each do |valid_email|
#user.email = valid_email
expect(#user.email).to be_valid
end
end
end
Please be make sure you've created a fixure for user in your fixures folder.
Hope this helps!

Resources