1

我的 Ability.rb 中定义了以下能力:

if user.role? :chief
   can [:action1, :action2], Request, user: {id: user.subordinate_ids}
end

在我的能力测试中,我有以下几点:

subject{ Ability.new(user) }
let(:user) { create(:chief_user) }
let(:subordinate) { create(:user, boss: user) }

it { is_expected.to be_able_to([:action1, :action2], Request.new(user: subordinate)) }

该功能在进行手动测试时按预期工作,但我无法使此测试工作。我已经使用适当的参数尝试了 Request.create,但我仍然得到相同的结果。

我做了一些调试,相应的关联是有序的(主管有下属,请求属于下属,所以实际测试一个主管只能action1,action2他的下属的请求)。

我正在使用 CanCanCan 和 RSpec 进行测试。

关于如何进行此测试的任何见解?

4

2 回答 2

0

rspec's let syntax is basically using a Proc (lazy loading) so until you call it it doesn't actually get persisted. when you call it in a spec sometimes you're testing something that hasn't been persisted yet.

You could check this by adding a before block

subject{ Ability.new(user) }
let(:user) { create(:chief_user) }
let(:subordinate) { create(:user, boss: user) }

it { is_expected.to be_able_to([:action1, :action2], Request.new(user: subordinate)) }

Try adding the before line below

subject{ Ability.new(user) }
let(:user) { create(:chief_user) }
let(:subordinate) { create(:user, boss: user) }

# new line to ensure object exists before test run
before {expect(subordinate).to eq subordinate}

it { is_expected.to be_able_to([:action1, :action2], Request.new(user: subordinate)) }

kind of frustrating IMO but I've run up against this before

于 2015-01-05T17:37:49.293 回答
0

Solved this by doing this:

subject{ Ability.new(user) }
let!(:user) { create(:chief_user) }
let!(:subordinate) { create(:user, boss: user) }
[:action1, :action2].each do |action|
    it { is_expected.to be_able_to(action, Request.new(user: subordinate)}
end

It didn't work by doing it together.

于 2015-01-05T17:37:52.887 回答