Home > Software design >  Meta programing and referring
Meta programing and referring

Time:10-12

I am trying to write a test for my scopes in my model.

 it "returns user that are manager" do
   user = FactoryBot.create(:user, manager: true)
   expect(User.is_manager(true)).to include(user)
 end
 it "returns user that are not manager" do
   user = FactoryBot.create(:user, manager: false)
   expect(User.is_manager(false)).to include(user)
 end

This is really simple and strait forward but I have close to 20 of this methods

What I want to do is something closer to this

describe 'scopes' do
    [
      {name: :is_manager, column: :manager},
      {name: :is_foo, column: :foo},
      {name: :can_baz,  column: :baz}
    ].each do |scope|
      it "returns user that are #{scope[:column]}" do
        user = FactoryBot.create(:user, scope[:column] true) # this line is given me a prolem
        expect(User::Permission.send(scope[:name](true)).to include(user)
      end
   end
  end

CodePudding user response:

in your case, i could do so

describe 'user scopes' do
    {
      :is_manager => [[true], {manager: true}],
      :is_foo => [[], {foo: true}],
      :not_foo => [[], {foo: false}],
      :by_name => [["%name%"], {name: "a name"}]
    }.each do |scope, (scope_args, model_args)|
      it "#{scope} should returns appropriate users" do
        user = FactoryBot.create(:user, **model_args)
        expect(User::Permission.send(scope, *scope_args)).to include(user)
      end
   end
  end

Or you could change

{
 [:is_manager, [true]] => {manager: true}
}.each do |(scope, scope_args), model_args|
  # ...
end
  • Related