[英]CanCan in RSpec Controller spec
I spent most of the day trying to root out a problem with a controller spec, and the current workaround seems unacceptable to me. 我一整天的时间都在尝试解决控制器规格方面的问题,而当前的解决方法对我来说似乎是不可接受的。 Any take on why this works?
为什么这样做有效? ... and what I should do instead.
...以及我应该怎么做。
Given a simple hierarchy as follows, and the following ability.rb, the properties_controller_spec.rb does not allow the spec below to pass without the line saying: 给定一个简单的层次结构,如下所示,并具有下面的capability.rb,properties_controller_spec.rb不允许下面的规范通过而无需说:
ability = Ability.new(subject.current_user)
Can you tell me why this would be? 你能告诉我为什么会这样吗?
Thanks! 谢谢!
Models: 楷模:
class Account < ActiveRecord::Base
has_many :properties, :dependent => :nullify
end
class Property < ActiveRecord::Base
belongs_to :account
end
class User < Refinery::Core::BaseModel #for RefineryCMS integration
belongs_to :account
end
Ability.rb: Ability.rb:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.has_role? :user
can [:read, :create, :update, :destroy], Property, account_id: user.account_id
else
can [:show], Property
end
end
end
properties_contoller_spec.rb: properties_contoller_spec.rb:
require 'spec_helper'
describe PropertiesController do
def valid_attributes
describe "Authenticated as Property user" do
describe "PUT update" do
describe "with invalid params" do
it "re-renders the 'edit' template" do
property = FactoryGirl.create(:property, account: property_user.account)
# Trigger the behavior that occurs when invalid params are submitted
Property.any_instance.stub(:save).and_return(false)
ability = Ability.new(subject.current_user) # seriously?
put :update, {:id => property.to_param, :property => { }}, {}
response.should render_template("edit")
end
end
end
end
end
Arg! 啊! Found it myself.
我自己找到的。
Here it is: 这里是:
config.include Devise::TestHelpers, :type => :controller
Following is the code to sign in the property_user, as directed by the Devise docs. 以下是在Devise文档的指导下登录property_user的代码。 (The locals in question are created in a global_variables.rb that is included. These are used all over the place.)
(有问题的本地人在其中包含的global_variables.rb中创建。这些本地人在各处使用。)
def signed_in_as_a_property_user
property_user.add_role "User"
sign_in property_user
end
def sign_in_as_a_property_user
property_user.add_role 'User'
post_via_redirect user_session_path,
'user[email]' => property_user.email,
'user[password]' => property_user.password
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.