如何对返回设置rspec的方法进行存根

问题描述 投票:0回答:1

我需要对返回集合的方法async_actions_set进行存根处理。我该怎么办?我尝试了多种方式,例如

class_name.any_instance.stubs(:async_actions_set?).returns([1, 2].to_set)

在我的模型中,这是我需要存根的条件

act_hash[:name].in?(async_actions_set)

但是它失败了。请帮忙async_actions_set返回一个集合

ruby rspec set minitest stub
1个回答
0
投票
irb(main):001:0> act_hash = { "name" => "eins", "age" => "20"}
irb(main):005:0> require 'set'
=> true
irb(main):006:0> r = ["eins", "zwei", "drei"].to_set
=> #<Set: {"eins", "zwei", "drei"}>
#Consider your async_actions_set function return above set r
# r = async_action_set

irb(main):008:0> require 'rspec'
=> true
irb(main):009:0> require 'rspec/expectations'
=> true
irb(main):010:0> singleton_class.prepend RSpec::Matchers
=> #<Class:#<Object:0x00000000026762c0>>

#Copied hash value to variable
irb(main):014:0> t = act_hash["name"]
=> "eins"

irb(main):015:0> expect(r.include?(t)).to be_truthy
=> true

# beacuse eins hash value present in Set

# Now i will change the value of t variable which is not preset in Set

irb(main):016:0> t = "batman"
=> "batman"
irb(main):017:0> expect(r.include?(t)).to be_truthy
Traceback (most recent call last):
       10: from C:/Ruby25-x64/bin/irb.cmd:19:in `<main>'
        9: from (irb):17
        8: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/expectation_target.rb:65:in `to'
        7: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/handler.rb:48:in `handle_matcher'
        6: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/handler.rb:27:in `with_matcher'
        5: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/handler.rb:50:in `block in handle_matcher'
        4: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/handler.rb:40:in `handle_failure'
        3: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-expectations-3.9.1/lib/rspec/expectations/fail_with.rb:35:in `fail_with'
        2: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-support-3.9.3/lib/rspec/support.rb:106:in `notify_failure'
        1: from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/rspec-support-3.9.3/lib/rspec/support.rb:97:in `block in <module:Support>'
RSpec::Expectations::ExpectationNotMetError (expected: truthy value)
     got: false

In your rspec file, please make sure you are adding || require 'set' || statement
© www.soinside.com 2019 - 2024. All rights reserved.