这是我的规范:
it "should successfullly destroy that user record" do
expect {
delete :destroy, :id => @user1.id
}.to change{User.count}.by(-1)
end
在UsersController
def destroy
@user = User.find(params[:id])
if @user.destroy
redirect_to root_path, notice: "You have successfully cancelled your account."
else
redirect_to :back
end
end
但是当我运行该规范时,我得到了这个:
RSpec::Expectations::ExpectationNotMetError: expected result to have changed by -1, but was changed by 0
我该如何解决这个问题?
修改1
@user1
正在before_each
调用context
阻止位于it
声明所在的context "when the inviter is being deleted and invited has not accepted invitation" do
before :each do
@user1 = create(:user, gender: 0)
@user2 = create(:user)
@member = create(:member, email: @user2.email, first_name: @user2.first_name, last_name: @user2.last_name, bio: @user2.bio, gender: @user2.gender)
@membership = create(:membership, member: @member, family_tree: @user1.family_tree, inviter: @user1, relation: "sister")
@connection = create(:connection, inviter_membership: @membership)
login_user
end
块中进行初始化。看起来像这样:
it "should successfullly destroy that user record" do
delete :destroy, id: @user1
expect(response).to redirect_to(root_path)
# expect {
# delete :destroy, id: @user1
# }.to change(User,:count).by(-1)
end
修改2
当我用这个换掉测试时,它可以工作:
Finished in 1.2 seconds (files took 6.08 seconds to load)
19 examples, 0 failures, 15 pending
该测试成功通过。
UsersController
编辑3
对于它的价值,我的load_and_authorize_resource
我在顶部打电话ability.rb
。当我删除它时,测试似乎确实通过了。所以问题是,如何让它与CanCanCan一起使用?
这就是我class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.has_role? :admin
can :manage, :all
end
can :manage, FamilyTree, user_id: user.id
can :manage, Comment, user_id: user.id
can :manage, Node, user_id: user.id
can :manage, Event, user_id: user.id
can :manage, User, id: user.id
can :read, Comment, user_id: user.id
can :read, Event, user_id: user.id
end
end
的样子:
raise
编辑4
当我在destroy
动作中添加destroy
时,没有任何反应。所以看来我的login_user
动作确实没有被执行。
编辑5
这就是我的module SpecAuthentication
def login_user
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create :user
sign_in @user
end
end
方法:
fspe2 = [fspe(t2,x) for t2 in t] TypeError: 'list' object is not callable
答案 0 :(得分:2)
规范未点击您的destroy
操作,请检查是否存在某种 before_action 阻止它这样做。
我会做这样的事情:
def destroy
raise # The action was hit
@user = User.find(params[:id])
if @user.destroy
redirect_to root_path, notice: "You have successfully cancelled your account."
else
redirect_to :back
end
end
答案 1 :(得分:2)
使用CanCanCan
gem,您必须允许控制器操作。您需要将其添加到ability.rb
文件中。
can :destroy, User
这将允许具有该角色的任何人销毁用户对象。您可以添加更多细节以适合您的使用案例。
编辑:刚看到CanCanCan gem上的:manage
文档。
您的能力文件目前允许用户自行管理。当您的测试试图销毁单独的用户时,您的login_user
方法正在动态创建用户。假设您使用current_user.id
方法,您可以更新CanCan能力以销毁所有用户或尝试销毁current_user
。我强烈建议您更改login_user
方法以接受用户对象,以便您知道哪个用户已登录并有权访问该对象。
编辑:
如上所述,使用一种方法对特定用户进行签名,以便您可以将其作为对象进行访问。将login_user
调用替换为sign_in @user1
或接受用户对象的类似方法。