我仍然能够快速掌握我的Ruby技能。
我一直试图弄清楚我是否可以为rspec测试干掉这段代码:
require 'rails_helper'
RSpec.describe Role, type: :model do
describe "has several roles types " do
before :each do
@roles = Role.all
end
context "The role types that are valid" do
it "includes 'proofreader', 'admin', 'super_admin' " do
expect(@roles.any?{|r| r.name == 'proofreader'}).to be_truthy
expect(@roles.any?{|r| r.name == 'admin'}).to be_truthy
expect(@roles.any?{|r| r.name == 'super_admin'}).to be_truthy
end
end
context "The role types that are not valid " do
it "includes 'developer' " do
expect(@roles.any?{|r| r.name == 'developer'}).to be_falsy
end
end
end
end
具体来说,我想将这三行代码减少到一行,但是我不知道如何在一行中检查三个字符串值的ActiveRecord关系。 有什么想法吗?
答案 0 :(得分:6)
您似乎需要使用include
匹配器:
it "includes 'proofreader', 'admin', 'super_admin' " do
expect(@roles.map(&:name)).to include('proofreader', 'admin', 'super_admin')
end
此外,您可以删除before
阻止,只需使用Role.pluck(:name)
:
let(:roles_names) { Role.pluck(:name) }
it '...' do
expect(roles_names).to include('proofreader', 'admin', 'super_admin')
end