非常简单,但我不知道如何通过测试。
我有一个要测试的 friendships
Controller (我正在构建类似于 this railscast 的 Rails 应用程序)。它适用于本地主机。这是我创建的测试。 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
这是实际控制人:
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
我还确保 routes.rb
有友谊:resources :friendships
我遇到的问题是传递 ID。我不知道如何传递 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]
我搜索其他 SO destroy
相关的帖子,比如 this one , this , 但它们与我的情况不同。
如何为销毁操作传递 ID 参数?
编辑:(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>
最佳答案
由于您要寻找的是友谊,而不是 Controller 中的用户,因此您需要先建立友谊。在此之前,您还需要知道要登录的用户。尝试先发送:
module ControllerMacros
def login_user(user)
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user ||= FactoryGirl.create(:user)
sign_in user
end
end
end
现在测试看起来像这样:
let(:current_user) { FactoryGirl.create(:user) }
login_user(current_user)
describe "DELETE #destroy" do
it "removes a friend =(" do
friendship = current_user.friendships.create!(friend_id: @friend1.id)
expect {
delete :destroy, id: friendship.id
}.to change(Friendship, :count).by(1)
end
end
你现在应该可以走了。
关于ruby-on-rails - 如何在删除:destroy in Rails?中传递ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46311829/