Rake Unit Testing : "False" being used for column "no" - ruby-on-rails

Post :: Model
class Post < ActiveRecord::Base
attr_accessible :body, :name, :no, :num
end
Posts.yml under (test/fixtures/)
one:
name: MyString
body: MyString
no: 1
num: 2
On running, rake test:units, the following stack trace is generated
Error:
test_Post_for_correct_attributes(PostTest):
ActiveRecord::StatementInvalid: SQLite3::SQLException: table posts has no column named false: INSERT INTO "posts" ("name", "body", "false", "num", "created_at", "updated_at", "id") VALUES ('MyString', 'MyString', 1, 2, '2012-12-26 10:24:36', '2012-12-26 10:24:36', 980190962)
Now, here - the table field 'no' has been converted to 'false'. (which seems to be a problem since its being interpreted as FALSE and not as a object variable)
A bug with how it is converting the variables from yaml to object?
Rails version Rails 3.2.9 and Ruby ruby 1.9.3p194

That seems like bug to me since Rails should be able to pick up on that, especially since this is autogenerated. Anyway, as a temporary workout, you can use:
one:
name: MyString
body: MyString
"no": 1
num: 2

Related

Ruby on Rails Testing - ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: malformed array literal:

I have a project that is running ok on production and development and mostly on many tests, but with one model there's no way to run the tests.
Model:
create_table "cities", force: :cascade do |t|
t.string "city"
t.string "cp", array: true
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.string "primary_cp"
end
(Note that "cp" attribute is an Array and I'm using Postgres on the project)
(I'm NOT setting "serialize: cp, Array" on the model)
But when I run rails test/models/city_test.rb what I get is
Error:
CityTest#test_the_truth:
ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:
malformed array literal: "MyString"
LINE 28: ...d_at") VALUES (980190962, 'MyString', 'MyString',
'MyString'...
^
DETAIL: Array value must start with "{" or dimension information.
: DELETE FROM "homes";
DELETE FROM "categories";
DELETE FROM "volunteers";
DELETE FROM "donations";
I've already searched for other solutions here but it doesn't fix the problem. What I'm guessing is that it is something related to the YAML serialization that the test environment does, but I'm not quite sure.
I have no problem with development and production environments at all, it only happens on test env.
For those who came up with same situation. the problem was with the declaration of the test fixtures. An array in YAML must be declared this way:
one:
city: Premià de Mar
cp:
- 08400
- 08401
two:
city: Mataró
cp:
- 08300
- 08301
Where "cp" is the array. Setting up the array properly fixes the issue.

Weird Rails migration / schema.rb issue

A while back I ran the following migration:
class CreatePipelineSpecs < ActiveRecord::Migration
def change
create_table :pipeline_specs do |t|
t.integer :id_no
t.string :od
t.string :wt
t.string :material
t.string :spec_type
t.string :spec_grade
t.string :mop
t.string :stress_level
t.string :joints
t.text :notes
t.string :ip
t.references :pipeline, index: true, foreign_key: false
t.timestamps null: false
end
add_index :pipeline_specs, :id_no
end
end
I am not sure what has happened now but every time I run rake db:migrate the scheme.rb file gets updated with:
create_table "pipeline_specs", force: :cascade do |t|
t.integer "id_no"
t.string "od"
t.string "wt"
t.string "material"
t.string "spec_type"
t.string "spec_grade"
t.string "mop"
t.string "stress_level"
t.string "joints"
t.text "notes"
t.string "ip"
t.integer "pipelines_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "pipeline_specs", ["id_no"], name: "index_pipeline_specs_on_id_no", using: :btree
add_index "pipeline_specs", ["pipelines_id"], name: "index_pipeline_specs_on_pipelines_id", using: :btree
Note the plural pipelines_id. The actual database tables (dev, production etc.) are all pipeline_id which is correct as the reference table is Pipeline. So I add a new unrelated migration and the schema.rb gets updated and these get changed back to plural again after I change them back. If I forget to change them when I run tests everything breaks as the wrong schema gets loaded into the test environment.
I am at a loss here. I am I missing something obvious here or is there some hidden migration schema table etc.
The only think I can this of is when I made the original migration I used pipelines:references vs pipeline:references, then fixed my mistake, and then cleaned up the migrations before committing this and deploying it.
Any ideas here one why this is happening and how to fix it once and for all?
UPDATE
Here are my three related models:
irb(main):031:0> Pipeline
=> Pipeline(id: integer, licence: string, company: string, company_id: integer, ba_code: string, substance_code: string, substance: string, h2s: string, partial_pressure: string, notes: text, created_at: datetime, updated_at: datetime, slug: string)
irb(main):032:0> PipelineSpec
=> PipelineSpec(id: integer, id_no: integer, od: string, wt: string, material: string, spec_type: string, spec_grade: string, mop: string, stress_level: string, joints: string, notes: text, ip: string, pipeline_id: integer, created_at: datetime, updated_at: datetime, slug: string)
irb(main):033:0> PipelineSegment
=> PipelineSegment(id: integer, line: integer, lsd_from: integer, sec_from: integer, twp_from: integer, rge_from: integer, m_from: integer, fc_from: string, lsd_to: integer, sec_to: integer, twp_to: integer, rge_to: integer, m_to: integer, fc_to: string, length: string, aasm_state: string, state_comment: string, state_user_id: integer, aasm_date: datetime, env: string, volume: string, notes: text, pipeline_id: integer, pipeline_spec_id: integer, created_at: datetime, updated_at: datetime, slug: string)
Pipeline has_many PipelineSpec and PipelineSegment. PipelineSegment has_one PipelineSpec.
UPDATE 2
Checked my test environment schema - it's fine. Ran rake db:migrate and again the schema.rb gets updated. Run the tests again and get gobs of:
ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "pipeline_id" of relation "pipeline_specs" does not exist
LINE 1: ..., "mop", "stress_level", "joints", "notes", "ip", "pipeline_...
^
: INSERT INTO "pipeline_specs" ("id", "id_no", "od", "wt", "material", "spec_type", "spec_grade", "mop", "stress_level", "joints", "notes", "ip", "pipeline_id", "created_at", "updated_at") VALUES (1, 1, '88.9', '3.18', 'S', 'Z245.1', '359 2', '9930', '25', 'W', 'MyText', 'U', 1, '2017-04-24 03:47:26', '2017-04-24 03:47:26')
as the fixtures try to load into the incorrect test schema that was just loaded at test time.
The schema is recreated from the actual state of your database after each migrations run. So I guess the pipelines_id must indeed exist somewhere in your db or at least Rails must think it exists in the db. I would do the following to narrow the issue down:
Run rake db:schema:dump SCHEMA=myschema.rb - this will generate a differently-named schema file manually. This is the same rake task that is also run after the migrations. I expect that the new schema will contain the plural pipelines_id column, too.
Then I'd take a look in the log/development.log (or whatever environment you are experiencing the issue in). You should see SELECT schema_migrations.* FROM schema_migrations and a bunch of further queries for showing structure of each table in your database there. Find the query that deals with the pipeline_specs table and run it manually in the db console to see what you precisely get. My expectation is that you'll either:
see the plural pipelines_ids there too - that would prove the column indeed exists in the db
or not - in which case I would restart everything I could in rails just to be sure there is no caching involved anywhere - specifically I'd restart spring with spring stop. Also I'd check (don't know Postgres that well to tell for sure) whether there might be any caching involved on the Postgres side. Then I'd try again.
I think that because the migration you deleted did't run on test environment, try reset the test database by:
RAILS_ENV=test rake db:migrate:reset
Try to specify a foregein_key in model PipelineSpec to pipelines_id
class PipelineSpec < ActiveRecord::Base
belongs_to :pipeline, foreign_key: :pipelines_id
end

Set table name dynamically, a bug?

database.yml looks like
development:
adapter: mysql2
host: localhost
database: database1
username: root
password:
external:
adapter: mysql2
host: localhost
database: database2
username: root
password:
I have a class ExternalDatabaseConnection
class ExternalDatabaseConnection < ActiveRecord::Base
self.abstract_class = true
establish_connection(:external) #connect to external DB specified in database.yml
attr_protected
end
I'm using AR to query on my external DB.
database2(external DB) is set dynamically from user end and I will not have any information about the tables and attributes.
database1(internal DB) which contains information about tables and some attributes.
So basically I have to handle things dynamically.
Works fine.
ExternalDatabaseConnection.table_name = "set_table1" #dynamic
ExternalDatabaseConnection.create(...) #creates a record.
This doesn't.
ExternalDatabaseConnection.table_name = "set_different_table" #dynamic
ExternalDatabaseConnection.create(...)
throws
unknown attribute: attribute_name
Both the things happen in loop, so every-time it works good for initial table set, for the second table, it throws an error.
Debugging:
Note:
ExternalDatabaseConnection.table_name = "payments"
ExternalDatabaseConnection.column_names
=> ["id", "customer_id", "patent_id", "amount", "currency", "date"]
ExternalDatabaseConnection.table_name = "patents"
=> "patents"
2.0.0-p451 :006 > ExternalDatabaseConnection.column_names
=> ["id", "customer_id", "patent_id", "amount", "currency", "date"]
ExternalDatabaseConnection.all
ExternalDatabaseConnection Load (0.4ms) SELECT `patents`.* FROM `patents`
=> [#<ExternalDatabaseConnection id: 1, number: "1111", description: "https://www.google.co.in", registry_date: "2014-08-20", documnetdir: nil, currency: #<BigDecimal:a8f2adc,'0.1212E2',18(27)>>, #<ExternalDatabaseConnection id: 4, number: "1", description: "jhufgtrdfyuh", registry_date: nil, documnetdir: "", currency: #<BigDecimal:a8f2258,'0.0',9(18)>>, ....]
There is no change in attributes, may be this is causing a problem.
If any information is missing, comment up.
ruby 2.0.0p451
Rails 3.2.17
edit1:
Tries:
Before setting table name
1) ExternalDatabaseConnection.table_name = nil .
2) ExternalDatabaseConnection.clear_active_connections! and clear_all_connections!
3) tried with set_table_name :table1
edit2:
ClassName.column_names is not getting changed even after setting different table_name for the Class
I have tried this following way. It may help
:set_table_name method is used to change the table name dynamically. You can set the table name and get the attributes name instead of columns name.
For payments table
ExternalDatabaseConnection.set_table_name :payments
ExternalDatabaseConnection.first.attribute_names
Then you have to reset the column information
ExternalDatabaseConnection.reset_column_information
For patents:
ExternalDatabaseConnection.set_table_name :patents
ExternalDatabaseConnection.first.attribute_names

Mysql2::Error: Incorrect date value: '--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess

I moved from sqllite to mysql (recreated the same workspace with mysql right from the beginning. Did not do any migrations).
The code worked well with sqllite but is erroring out with mysql. This is how my database.yml looks like:
development:
adapter: mysql2
database: dev
username: root
password:
host: localhost
pool: 5
My code takes in a date through a date select in the view:
<%= date_select(:dob, NIL, :use_short_month => true, :start_year => Time.now.year - 100,
:end_year => Time.now.year, :order => [:day, :month, :year]) %>
The model looks like this:
t.string "firstName"
t.string "lastName"
t.string "Email"
t.string "password"
t.date "dob"
But the insert through the following code in the controller fails:
#user.dob = params[:dob]
This is the error I get:
Mysql2::Error: Incorrect date value: '--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
(1i): '2013'
(2i): '4'
(3i): '18'
' for column 'dob' at row 1: INSERT INTO `users` (`Email`, `created_at`, `dob`, `firstName`, `lastName`, `password`, `personalEmail`, `updated_at`) VALUES ('abc#xyz.com', '2013-04-18 15:46:26', '--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\n(1i): \'2013\'\n(2i): \'4\'\n(3i): \'18\'\n', 'ABC', 'XYZ', 22, NULL, 'ab4d8d2a5f480a137067da17100271cd176607a1', '2013-04-18 15:46:26')
I had googled quite an extent but couldnt find any references to this. Appreciate any leads or help on this.
the problem is the multiparameter thing. rails date_select helper generates 3 dropdowns which pass 3 different parameters to your controller. if you use mass assignment in your controller, rails magically converts these 3 values to 1 date value. this (quite old) blog post shows a way to do it without mass-assignment: http://www.springenwerk.com/2008/05/set-date-attribute-from-dateselect.html
but, this post is rather old, and there could(!) be a better way by now
Whats clear to me is that the dat object is not formatted correctly for the mysql database. Try something like
#user.dob = params[:dob].to_date
Try formatting the date object in different ways to see what works. It may also help to open up rails console and try working things out manually. Let me know how that goes.
-Brian

Unset operation failing for MongoMapper model, cannot delete / remove key from model

We're on mongodb 2.0.0, mongo gem 1.4.1, mongo_mapper 0.9.2, rails 3.0.6.
We love MongoMapper, but we need helping resolving one nasty issue: we have a key carried over from some testing, but invoking obj.unset fails to do anything.
Specifically, we are trying to remove an "id" key (not "_id") because it's causing MM to treat obj.id as different from obj._id, which we don't want.
After clearing out the database, we ran these commands from a controller which does nothing else: (We also tried running the same code from the rails console, but it also fails.)
logger.info "#{Game.keys.keys.inspect}"
Game.unset({}, :id)
logger.info "#{Game.keys.keys.inspect}"
Game.unset(:id)
logger.info "#{Game.keys.keys.inspect}"
Output:
["jackpot", "players", "created_at", "puzzles", "ended_at", "player_index", "updated_at", "log", "_id", "id", "join_code", "puzzle_index"]
["jackpot", "players", "created_at", "puzzles", "ended_at", "player_index", "updated_at", "log", "_id", "id", "join_code", "puzzle_index"]
["jackpot", "players", "created_at", "puzzles", "ended_at", "player_index", "updated_at", "log", "_id", "id", "join_code", "puzzle_index"]
Current keys defined in our Game model:
key :players, Array, :default => []
key :player_index, Integer, :default => 0
key :puzzles, Array, :default => []
key :puzzle_index, Integer, :default => 0
key :join_code, String, :default => nil
key :jackpot, Integer, :default => 0
key :log, Array, :default => []
key :created_at, Time
key :updated_at, Time
key :ended_at, Time, :default => nil
Help?
Thanks!
It pains us to post the answer since this solidifies our status as "morons, idiots, fools, noobs, Jay Leno fans," but in case anyone else bumps into the same issue: while our model directory was clean in the dev environment, the model dir in the production environment contained old test files ... which contained an old model with the "id" key.
Obviously, removing the old files and the old models solved everything, though we're left with staggering bruises to our egos and to our heads (from excessive banging against the walls).

Resources