I am new to RoR. I have two problems here.
ISSUE 1
my rspec is
require 'spec_helper'
describe RefUserCategory do
describe "validations" do
it { should validate_presence_of(:user_category_description) }
end
end
my Ref_User_Category model is
class RefUserCategory < ActiveRecord::Base
validate :user_category_description , presence: true
has_many :Users
end
The error I got in Rspec is
Expected errors to include /can't be blank/ when user_category_description is set to nil, got no errors
So I decided to to use Pry to check whats happening
ISSUE 2
Im my application folder I do
pry -r ./config/environment
[2] pry(main)> Ref_User_Category.new
LoadError: Unable to autoload constant Ref_User_Category, expected /var/lib/stickshift/52d29d0e5004461024000031/app-root/data/736003/east/app/models/ref_user_category.rb to define it
from /var/lib/stickshift/52d29d0e5004461024000031/app-root/data/lib/ruby/gems/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:464:in `load_missing_constant'
I have user model too I
pry(main)> User.new
gives error
ActiveRecord::StatementInvalid: Could not find table 'users'
/app-root/data/lib/ruby/gems/gems/activerecord-4.0.2/lib/active_record/connection_adapters/sqlite3_adapter.rb:512:in `table_structure'
Regarding issue 1, you have a typo: change validate to validates.
Regarding issue 2:
You generally start the console from the root of your project like this:
$ rails c
You are doing Ref_User_Category.new when you should do RefUserCategory.new.
About User.new, it looks like you haven't run your database migrations:
$ rake db:migrate
$ rake db:test:prepare
Related
1) created a model called Skill
2) ran some seeds
3) ran rspec --init
4) created file skill_spec.rb with the code below
require_relative "../app/models/skill"
describe Skill do
describe "database" do
it "should have 42 skills" do
expect(Skill.all.count).to eq(42)
end
end
end
5) when I run rspec in console get error:
Failure/Error: class Skill < ApplicationRecordNameError:
uninitialized constant ApplicationRecord
I already have a file application_record.rb with the following code
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
For rails specs use require 'rails-helper' at beginning of each spec file (it is generated by bin/rails generate rspec:install from rspec-rails gem)
It contains line require File.expand_path('../config/environment', __dir__) that will load your rails environment and you'll have autoloading and all other rails parts working.
I got a rake task which invokes other rake tasks, so my development data can be easily reset.
the first rake task (lib/tasks/populate.rake)
# Rake task to populate development database with test data
# Run it with "rake db:populate"
namespace :db do
desc 'Erase and fill database'
task populate: :environment do
...
Rake::Task['test_data:create_company_plans'].invoke
Rake::Task['test_data:create_companies'].invoke
Rake::Task['test_data:create_users'].invoke
...
end
end
the second rake task (lib/tasks/populate_sub_scripts/create_company_plans.rake)
namespace :test_data do
desc 'Create Company Plans'
task create_company_plans: :environment do
Company::ProfilePlan.create!(name: 'Basic', trial_period_days: 30, price_monthly_cents: 4000)
Company::ProfilePlan.create!(name: 'Professional', trial_period_days: 30, price_monthly_cents: 27_500)
Company::ProfilePlan.create!(name: 'Enterprise', trial_period_days: 30, price_monthly_cents: 78_500)
end
end
when I run bin/rake db:populate then i get this error
rake aborted! LoadError: Unable to autoload constant
Company::ProfilePlan, expected
/home/.../app/models/company/profile_plan.rb to define it
but when I run the second rake task independently it works well.
The model (path: /home/.../app/models/company/profile_plan.rb)
class Company::ProfilePlan < ActiveRecord::Base
# == Constants ============================================================
# == Attributes ===========================================================
# == Extensions ===========================================================
monetize :price_monthly_cents
# == Relationships ========================================================
has_many :profile_subscriptions
# == Validations ==========================================================
# == Scopes ===============================================================
# == Callbacks ============================================================
# == Class Methods ========================================================
# == Instance Methods =====================================================
end
Rails 5.0.1
Ruby 2.4.0
The App was just upgraded from 4.2 to 5
It works when I require the whole path:
require "#{Rails.root}/app/models/company/profile_plan.rb"
But this seems strange to me, because in the error message rails has the correct path to the Model. Does someone know why I have to require the file when invoked from another rake task?
Thank you very much
Well, it seems that rake doesn't eager load, so when you call the create_company_plans.rake alone it loads the referred objects, however when you invoke it from another rake, it doesn't know you will need them and so they are not loaded.
You can take a look at this other QA which was similar to yours.
I think maybe you don't need to require the whole path, just:
require 'models/company/profile_plan'
From what I understand, you can probably overcome the problem by reenable ing and then revoke ing the task as given below. Pardon me if this doesn't work.
['test_data:create_company_plans', 'test_data:create_companies'].each do |task|
Rake::Task[task].reenable
Rake::Task[task].invoke
end
There is more info on this stackoverflow question how-to-run-rake-tasks-from-within-rake-tasks .
In Rails 3.2.16, I have a model:
class Person < ActiveRecord::Base
module Testmodule
def testmethod
puts "It's included"
end
end
include Testmodule
end
when I run bundle exec rails c, I can type Person.new.testmethod and get the expected result
If I create a small rake task:
task :myraketask => :environment do
Person.new.testmethod
end
I receive an error that testmethod isn't defined on Person.
However, if I explicitely set eager loading in the rake task, it will work:
task :myraketask => :environment do
Rails.application.eager_load!
Person.new.testmethod
end
If I create a brand new Rails project, I cannot replicate the error. Can anybody point out to me what may be wrong in my project that is causing the error in the first rake task?
Trying to use FactoryGirl to seed my development db with some data. Following this tutorial so my seeds.rb file looks like this:
require 'factory_girl'
Dir[Rails.root.join("spec/factories/*.rb")].each {|f| require f}
100.times do
FactoryGirl.create :idea
end
When running rake db:seed it complains:
rake aborted!
Factory already registered: idea
Why is it a bad thing that the factory is registered? I'm trying to use it, not register it (whatever that means...). Any idea what I'm doing wrong?
Most likely your factories are already being loaded. Try removing the line that does each of the requires and see if that corrects the issue.
def mock_category(stubs={})
#mock_category ||= mock_model(Category, stubs).as_null_object
end
describe "GET show" do
it "assigns the requested category as #category" do
Category.stub(:find).with("37") { mock_category }
get :show, :id => "37"
assigns(:category).should be(mock_category)
end
end
Which returns :
1) CategoriesController GET show assigns the requested category as #category
Failure/Error: assigns(:category).should be(mock_category)
expected Category_1002, got nil
I'm confused here, because this is a right out of the box controller that rspec set up. Why could this be failing?
My versions:
Rails 3.0.0.beta4
Ruby 1.8.7
RSpec 2.0.0.beta.10
Also tried this, same exact reproducible error with :
Rails 3.0.0
Ruby 1.8.7
RSpec 2.0.0.beta.20
The command I used to generate the specs were rails g scaffold Category
In my application.rb
config.generators do |g|
g.template_engine :haml
g.test_framework :rspec, :fixture => true, :views => false
end
UPDATE
This goes for any scaffolded controller by Rails 3, with RSpec2. Its guarenteed to fail. Anyone know how this is supposed to be written?
rspec-rails has a spec-suite it runs against itself that uses all the generators and runs all the generated specs and they all pass, so this should work. What versions of rspec, rails, and ruby are you using? What commands did you use to generate the Category model and CategoriesController?
The conflict comes from conflicts that occurred between Rspec Beta 10 and Rspec Beta 20, and Rails 3 Beta4, to Rails 3 release.
To solve this, I uninstalled haml, and installed haml-rails.
Then I deleted all the specs that were previously generated, and regenerated them.