2

我有以下情况,

class Schools::Status
  def initialize(school)
    @school = school
  end

  def active?
    true
  end
end

现在,我想active?为特定学校存根方法。

拥有这样的一种方法

Schools::Status.new(school).stubs(:active?).returns(false)

但是我的用例不同,我有学校的搜索结果,我想根据active?以下值过滤该结果:

schools.select { |s| Schools::Status.new(school).active? }

在上述情况下,特别是我想active?为某些实例存根。

4

2 回答 2

3

Just monkey-patch your class in the spec.The more rspec-way would be to use any_instance with stub but the problem is you cannot get access to the self of the stubbed instance so you practicly have no information about the school and you cannot access it in that block. Example:

Status.any_instance.stub(:active?) { # no way to access school }
于 2014-08-19T08:10:37.870 回答
1

我找到了自己的答案并将其放在这里,以便其他人受益

可以说,我有school哪个active?方法Schools::Status要被存根。

为了实现这一点,首先我们需要存根new方法,Schools::Status以便它返回我们想要的 Schools::Status 实例,它可以如下完成 -

status = Schools::Status.new(school)
# now whenever Schools::Status instance getting created for ours school 
# it will return our defined status instance
Schools::Status.stubs(:new).with(school).returns(status)

其次,我们必须active?为状态实例存根方法 -

status.stubs(:active?).returns(false)

现在,过滤器将拒绝active?方法返回 false的指定学校

于 2014-08-19T09:39:40.140 回答