0
テストを実行中に次のエラーが発生しています。テストが合格する条件は、ユーザーが投稿を作成するためにログインする必要があることです。同様のエラーはforeign_keyとほとんど同じですが、私はそれを持っているようです。どんな助けでも大歓迎です。ありがとう!ActiveRecord :: UnknownAttributeError:不明な属性 'user_id' for Post
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: "[email protected]",
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
あなたのテストデータベースのようなサウンドは同期していません。削除して再作成してみてください –
助けてくれてありがとうございました – user5971196
Ok - 回答を追加しました。 –