如何测试CanCan';s:使用rspec创建
我正在尝试测试我的应用程序的CanCan:create规则。这是我的密码: 能力.rb 用户\控制器\规范rb 基本上,当我实际测试我的应用程序时,上面的代码工作得很好,但当我尝试运行测试时,它给了我:如何测试CanCan';s:使用rspec创建,rspec,ruby-on-rails-4,cancan,rspec-rails,Rspec,Ruby On Rails 4,Cancan,Rspec Rails,我正在尝试测试我的应用程序的CanCan:create规则。这是我的密码: 能力.rb 用户\控制器\规范rb 基本上,当我实际测试我的应用程序时,上面的代码工作得很好,但当我尝试运行测试时,它给了我: Failures: 1) User abilities when is a regular user is able to create a new node Failure/Error: should be_able_to(:create, Node.new) e
Failures:
1) User abilities when is a regular user is able to create a new node
Failure/Error: should be_able_to(:create, Node.new)
expected to be able to :create #<Node id: nil, title: nil, body: nil, user_id: nil, thumbnail: nil, created_at: nil, updated_at: nil, url: nil, site_id: nil, score: 0, shares_facebook: 0, shares_twitter: 0, status: nil>
故障:
1) 普通用户能够创建新节点时的用户能力
失败/错误:应该能够(:create,Node.new)
预期能够:创建#
如何测试这个:create方法?提前感谢您的帮助。我认为这里的问题是您的规范中的
用户
没有持久化FactoryGirl.build
返回一个新对象,但不将其保存到数据库中。因此,user.persistend?
将在您的能力中为假
简单的解决方法是使用FactoryGirl.create
,它确实会让用户持久化,尽管这会让您的测试稍微慢一点。是的,这肯定是有道理的,也是出现此问题的原因。谢谢!:)
require 'spec_helper'
require "cancan/matchers"
describe User do
let(:user) { FactoryGirl.build(:user) }
it "has a valid factory" do
expect(user).to be_valid
end
# ...
describe "abilities" do
subject(:ability) { Ability.new(user) }
let(:user) { nil }
# ...
context "when is a regular user" do
let(:user){ FactoryGirl.build(:user) }
it "is able to create a new node" do
should be_able_to(:create, Node.new)
end
it "is not able to edit existing node" do
@node = FactoryGirl.build(:node)
should_not be_able_to(:update, @node)
end
end
end
end
Failures:
1) User abilities when is a regular user is able to create a new node
Failure/Error: should be_able_to(:create, Node.new)
expected to be able to :create #<Node id: nil, title: nil, body: nil, user_id: nil, thumbnail: nil, created_at: nil, updated_at: nil, url: nil, site_id: nil, score: 0, shares_facebook: 0, shares_twitter: 0, status: nil>