元编程和引用

Meta programing and referring

我正在尝试为我的模型中的示波器编写测试。

 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

这真的很简单,但我有将近 20 个这样的方法

我想做的是更接近于此的东西

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

在你的情况下,我可以这样做

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

或者您可以更改

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