chell
chell

Reputation: 7866

How to clean up this test using better Ruby syntax

I am still getting my Ruby skills up to speed.

I have been trying to figure out if I can DRY out this code for an rspec test:

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

Specifically I want to reduce those three lines of code down to one but it has eluded me how to check an ActiveRecord relation for three string values in one line. Any ideas?

Upvotes: 1

Views: 71

Answers (1)

Ilya
Ilya

Reputation: 13487

It seems like you need to use include matcher:

it "includes 'proofreader', 'admin', 'super_admin' " do
  expect(@roles.map(&:name)).to include('proofreader', 'admin', 'super_admin')
end

Also, you can remove before block and just use Role.pluck(:name) instead:

let(:roles_names) { Role.pluck(:name) }
it '...' do
  expect(roles_names).to include('proofreader', 'admin', 'super_admin')
end

Upvotes: 6

Related Questions