我刚刚添加了Rolify gem,并且正在运行一些rspec测试。
2项测试如下:
describe "roles" do
before(:each) do
@user = FactoryGirl.create(:user)
end
it "should not approve incorrect roles" do
@user.add_role :moderator
@user.has_role? :admin
should be_false
end
it "should approve correct roles" do
@user.add_role :moderator
@user.has_role? :moderator
should be_true
end
end
测试结果是:
1) User roles should not approve incorrect roles
Failure/Error: should be_false
expected: false value
got: #<User id: nil, email: "", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, name: nil, position: nil, location: nil, admin: false, archived: false, public_email: false, created_at: nil, updated_at: nil>
# ./spec/models/user_spec.rb:70:in `block (3 levels) in <top (required)>'
Finished in 1.37 seconds
7 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:67 # User roles should not approve incorrect roles
Randomized with seed 13074
factories.rb
FactoryGirl.define do
factory :user do
sequence(:name) {|n| "Example User #{n}"}
sequence(:email) {|n| "email#{n}@program.com" }
position "Regular"
location "Anywhere, USA"
public_email false
password "foobar"
password_confirmation "foobar"
confirmed_at Time.now
end
end
第一个测试如何使用nil对象失败,但第二个测试是否通过?
修改
进一步检查后,should be_true
的任何测试都会通过,should be_false
的任何测试都会失败,无论添加的角色是否与已检查的角色匹配。
答案 0 :(得分:3)
当你的测试should be_true
发生了什么时,应该将调用委托给主题对象(参见RSpec docs for implicit receiver)。在这种情况下,您的主题对象是尚未保存到数据库的用户实例。如果您的user_spec.rb文件以describe User do
开头,则RSpec会自动提供User.new的默认主题(请参阅RSpec docs for implicit subject)。
这意味着您的测试基本上是User.new.should be_true
和User.new.should be_false
。由于User对象将始终评估为true,因此should be_true
测试将始终通过(尽管可能不是您想要的原因)并且be_false应始终失败。
根据您的测试编写方式,也许您的意思更像是这样:
describe "roles" do
before(:each) do
@user = FactoryGirl.create(:user)
end
it "should not approve incorrect roles" do
@user.add_role :moderator
@user.has_role?(:admin).should be_false
end
it "should approve correct roles" do
@user.add_role :moderator
@user.has_role?(:moderator).should be_true
end
end
答案 1 :(得分:1)
我假设示例组实际上嵌套在用describe User do
声明的组中,是吗?
问题是每个示例的最后一行读取should xxx
,但should
没有接收者,因此RSpec会替换User
的实例。
你想要的是:
describe User do
describe "roles" do
before(:each) do
@user = FactoryGirl.create(:user)
end
it "should not approve incorrect roles" do
@user.add_role :moderator
@user.has_role?(:admin).should be_false
end
it "should approve correct roles" do
@user.add_role :moderator
@user.has_role?(:moderator).should be_true
end
end
end
HTH, 大卫