【发布时间】:2018-07-03 01:10:50
【问题描述】:
使用 Rails 5.1.4、Ruby 2.4.1、rspec
场景:
在文章中销毁只允许角色为“a,m”的用户 current_ma_user
然后:
检查 current_ma_user.role = "a,m" 或 current_ma_user 自己的文章 (@article.user)
所以我创建 current_ma_user 作为哈希以及用户。 然后调用role来检查什么是user[role]
问题:
如何向哈希添加新方法。
如何将该 hash.method 从 rspec controller_spec 传递给控制器。
失败:
1) ArticlesController DELETE #destroy destroys the requested article
Failure/Error: delete :destroy, params: {id: article.to_param}, session: valid_session, :current_ma_user.role => "a,m"
NoMethodError:
undefined method `role' for :current_ma_user:Symbol
# ./spec/controllers/articles_controller_spec.rb:172:in `block (4 levels) in <top (required)>'
# ./spec/controllers/articles_controller_spec.rb:171:in `block (3 levels) in <top (required)>'
这是gist
articles_controller_spec.rb:
require 'rails_helper'
RSpec.describe ArticlesController, type: :controller do
class Hash #patch to temp pass problem 1
def role
"a,m" #Hard Code, need to call user["role"] need code
end
end
user = {}
user["uid"] = "admin"
user["provider"] = "Facebook"
user["email"] = "1.0@kul.asia"
user["role"] = "a,m"
current_ma_user = user
describe "DELETE #destroy" do
it "destroys the requested article" do
article = Article.create! valid_attributes
expect {
delete :destroy, params: {id: article.to_param}, session: valid_session
}.to change(Article, :count).by(-1)
end
it "redirects to the articles list" do
article = Article.create! valid_attributes
delete :destroy, params: {id: article.to_param}, session: valid_session
expect(response).to redirect_to(articles_url)
end
end
end
控制器:
class ArticlesController < ApplicationController before_action :load_article, only: [:show, :destroy]
def destroy
if current_ma_user.role.upcase.split(',').include?("A") || current_ma_user == @article.user
#if current_ma_user == @article.user
@article.destroy
end
redirect_to :action=>'index' end
private
def load_article
@article = Article.find(params[:id]) end
end
【问题讨论】:
-
您是否使用工厂来创建文章?如果有请发帖
-
不,我尝试创建用户和 current_ma_user 用于销毁,其他测试如创建,更新都可以
-
你能在
'` 中显示 # ./spec/controllers/articles_controller_spec.rb:172:inblock(4 个级别)吗 - 这个字符串(以及这个字符串周围的另一个) -
@kunashir 请查看更新的行是否足够或任何信息可能会有所帮助。谢谢
-
您的
current_ma_user在某些地方似乎被定义为Symbol,但您尝试像对象一样使用它并调用role。尝试分析此错误的回溯。愿你用完整的跟踪和完整的控制器代码做一个要点
标签: ruby-on-rails ruby methods hash rspec