これは非常にシンプルですが、テストをパスする方法を理解できません。削除でIDを渡すには:Railsで破壊する?
私はfriendships
コントローラを持っていました(私はthis railscastに似たRailsアプリケーションをビルドしています)。これはlocalhostで動作します。これは私が作成したテストです。 POST #create
が合格しました。
require 'rails_helper'
RSpec.describe FriendshipsController, type: :controller do
login_user
before :each do
@friend1 = FactoryGirl.create(:user)
end
describe "POST #Create" do
it "adds new friend" do
expect {
post :create, params: { friend_id: @friend1.id}
}.to change(Friendship, :count).by(1)
end
end
describe "DELETE #destroy" do
it "removes a friend =(" do
expect {
delete :destroy, id: @friend1.id
}.to change(Friendship, :count).by(1)
end
end
end
これは、実際のコントローラである:私もroutes.rb
が友情を持っていることを確認しました
class FriendshipsController < ApplicationController
def create
@friendship = current_user.friendships.build(friend_id: params[:friend_id])
if @friendship.save
flash[:notice] = "New friend added!"
redirect_to root_url
else
flash[:error] = "Error adding friend"
redirect_to root_url
end
end
def destroy
@friendship = current_user.friendships.find(params[:id])
@friendship.destroy
flash[:notice] = "Remove friendship"
redirect_to current_user
end
end
:私が午前resources :friendships
問題はID.Iできない姿を渡すことですid
パラメータを渡す方法を説明します。私はそれが私の工場と関係があると思う...?
1) FriendshipsController DELETE #destroy removes a friend =(
Failure/Error: @friendship = current_user.friendships.find(params[:id])
ActiveRecord::RecordNotFound:
Couldn't find Friendship with 'id'=159 [WHERE "friendships"."user_id" = $1]
私はthis one、thisのように、他のSO destroy
関連記事を検索し、彼らは私と異なる場合があります。
破壊アクションのIDパラメータを渡すにはどうすればよいですか?
EDIT:以下の答えによって示唆されるように(Source)
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
#user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
、私がやった:
describe "DELETE #destroy" do
it "removes a friend =(" do
friendship = user.friendships.create!(friend_id: @friend1.id)
expect {
delete :destroy, id: friendship.id
}.to change(Friendship, :count).by(1)
end
end
しかし、それは今、このエラーが返されます。あなたのよう
FriendshipsController DELETE #destroy removes a friend =(
Failure/Error: friendship = user.friendships.create!(friend_id: @friend1.id)
NameError:
undefined local variable or method `user' for #<RSpec::ExampleGroups::FriendshipsController::DELETEDestroy:0x007fee1ce68c70>
ありがとう、@Babar!私は進歩を遂げましたが、私はまだ問題を抱えています。 '未定義のローカル変数またはメソッドuser'。私は 'login_user'と私の新しいDELETEテストの中に何が入っているのかを解答しました。私が間違ったことを知っていますか? – Iggy
私は自分の答えを更新しました。今は良いはずです。 – Babar