Sajad Torkamani
Sajad Torkamani

Reputation: 670

Why am I getting unknown column when the column exists?

When running my spec for photos#star, I'm not sure why I am getting the unknown column error for stars.user_id when the column actually exists. The action works fine in the rails console and in the browser in that the @user.starred_photos actually gets modified.

I've checked the database schema in mysql and the column is there. I've tried rolling back the migration and redoing it as well as restarting the server. This is the error:

Failure/Error:
   expect{
     post :star, id: photo
   }.to change{ @user.starred_photos.count }.from(0).to(1)

 ActiveRecord::StatementInvalid:
   Mysql2::Error: Unknown column 'stars.user_id' in 'where clause': SELECT COUNT(*) FROM `photos` INNER JOIN `stars` ON `photos`.`id` = `stars`.`photo_id` WHERE `stars`.`user_id` = 1

Controller spec & action

# spec/controllers/photos_controller_spec.rb   
describe '#POST star' do
    it "adds the given photo to the user's starred photos" do
        sign_in_as_user
        other_user = create(:user)
        photo = other_user.photos.create(attributes_for(:photo))

        expect{
            post :star, id: photo
        }.to change{ @user.starred_photos.count }.from(0).to(1)
    end
end


#app/controllers/photos_controller.rb
def star
    current_user.starred_photos << @photo
end 

Models

# app/models/star.rb
class Star < ActiveRecord::Base
  belongs_to :user
  belongs_to :photo
end

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :photos
  has_many :stars
  has_many :starred_photos, through: :stars, source: :photo

# app/models/photo.rb
class Photo < ActiveRecord::Base
  belongs_to :user
  has_many :stars
  has_many :starring_users, through: :stars, source: :user

Schema

# db/schema.rb
create_table "stars", force: :cascade do |t|
    t.integer  "photo_id",   limit: 4
    t.integer  "user_id",    limit: 4
    t.datetime "created_at",           null: false
    t.datetime "updated_at",           null: false
end

I'm having one of those days and I suspect I'm missing something really obvious here. Thanks in advance!

Upvotes: 0

Views: 1051

Answers (1)

Robert Nubel
Robert Nubel

Reputation: 7522

Your test database has likely not had your migrations applied to it yet. You can run rake db:test:prepare to copy your development database schema to your test database, then try running your tests again. Or, you can just run rake spec -- by default, that command will prepare your test database before running any tests.

Upvotes: 1

Related Questions