使用RSpec测试是否设置了graphQL字段方法参数默认值

时间:2019-04-17 09:54:11

标签: ruby-on-rails ruby rspec graphql

如何编写测试以检查字段方法参数的默认值?

    field :foo, String, null: false do
      argument my_argument, Int, required: true
      argument my_other_argument, Boolean, required: false
    end

    def foo(my_argument:, my_other_argument: true)
      <some code>
    end

我在RSpec测试中的尝试:

    field :foo, "String!" do
      it "test that my_other_argument has a default value of true"
       resolve(args: {my_argument: 10}) # Note that my_other_argument is not given a value

       expect(args[:my_other_argument]).to eq(true)
      end
    end

以上示例失败并引发此错误:

undefined local variable or method `args'

因此,将其归结起来-似乎无法弄清楚应如何写此行:

expect(args[:my_other_argument]).to eq(true)

...还是我走错了路?

2 个答案:

答案 0 :(得分:0)

如果foo正在调用另一种方法,则可以使用recievewith。像...

class Foo
  def bar(my_other_argument: true)
    baz(my_other_argument)
  end

  def baz(val)
    # Stuff
  end
end

describe :bar do
  context 'default values' do
    it 'defaults to true' do
      @foo = Foo.new
      expect(@foo).to receive(:baz).with(true)

      @foo.bar
    end
  end
end

答案 1 :(得分:0)

让我们考虑一下Resolvers。 您可以为foo定义一个解析器。

class Resolvers::Foo < Resolvers::Base
  argument :my_argument, Int, required: true
  argument :my_other_argument, Boolean, required: false

  def resolve(my_argument:, my_other_argument: true)
    <some code>
  end
end

并在查询文件中将其用作

field :foo, String, resolver: Resolvers::Foo, null: false 

另一方面,如果要使用参数测试某些字段,最好使用以下参数进行查询:

foo(my_argument: $my_argument, my_other_argument: $my_other_argument)

$my_argument$my_other_argument是您要测试的参数。 Graphql testing

的文档中有更多详细信息