ActiveRecord :: UnknownAttributeError:帖子

时间:2016-08-05 06:52:50

标签: ruby-on-rails activerecord rspec tdd capybara

运行测试时遇到以下错误。测试通过的条件是用户必须登录才能创建帖子。类似的错误似乎主要与foreign_key有关,但我似乎有。任何帮助都感激不尽。谢谢!

Failure/Error: @post = current_user.posts.build(post_params)

 ActiveRecord::UnknownAttributeError:
   unknown attribute 'user_id' for Post.

NoMethodError:
 #   undefined method `user_id=' for #<Post:0x007fe1d0bf19e0>
 #   Did you mean?  user=
 #   ./app/controllers/posts_controller.rb:10:in `create'

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
end

user.rb

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

posts_controller.rb

def create
  @post = current_user.posts.new(post_params)
  ...
end

schema.rb

create_table "posts", force: :cascade do |t|
  t.string   "title"
  t.text     "body"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer  "user_id"
end

add_index "posts", ["user_id"], name: "index_posts_on_user_id"

rspec测试

require "rails_helper"

RSpec.describe "Creating post" do 
  let(:user) { User.create(username: "user", email: "mail@mail.com", 
  password: "password", password_confirmation: "password")}

  scenario "successfully" do 
    sign_in user
    visit root_path
    click_on "New Post"

    fill_in "Title", with: "title"
    fill_in "Body", with: "body"
    click_on "Submit"

    within (".content") do
      expect(page).to have_content("title")
      expect(page).to have_content("user")
    end
  end

  scenario "unsuccessfully" do 
    sign_in user
    visit root_path
    click_on "New Post"

    fill_in "Title", with: "Second Post"
    fill_in "Body", with: ""
    click_on "Submit"

    expect(page).to have_css ".error"
  end

  scenario "User not logged in cannot create posts" do 
    visit root_path
    click_on "New Post"

    expect(current_path).to eq(new_user_session_path)
  end
end

1 个答案:

答案 0 :(得分:0)

您的测试数据库不同步,删除并重新创建它。