RSpec如何存根收益并确保收益不被确保

时间:2018-12-09 01:04:59

标签: ruby unit-testing rspec rspec-rails

我有一个名为set_current_user的动作周围动作

def set_current_user
  CurrentUser.set(current_user) do
    yield
  end
end

在CurrentUser单例中

  def set(user)
    self.user = user
    yield
  ensure
    self.user = nil
  end

我无法弄清楚如何对收益率进行存根,而方法中没有保证部分的

理想情况下,我想做类似的事情

it 'sets the user' do
  subject.set(user)
  expect(subject.user).to eql user
end 

我遇到两个错误

    1. 未提供任何阻止
    1. 当我通过块时,self.user = nil被称为

预先感谢

3 个答案:

答案 0 :(得分:1)

需要指出的几件事可能会有所帮助:

print(df.info()) <class 'pandas.core.frame.DataFrame'> Int64Index: 20620 entries, 0 to 24867 Data columns (total 3 columns): neighborhood 20620 non-null object bedrooms 20620 non-null float64 price 20620 non-null float64 dtypes: float64(2), object(1) memory usage: 644.4+ KB 保留给想要运行的代码块,无论发生什么情况,因此ensure始终为self.user的原因。我认为您想要的是在有例外的情况下将用户分配为nil。在这种情况下,您应该改用nil

rescue

对于单元测试,您只想测试def set(user) self.user = user yield rescue => e self.user = nil end 类中的.set方法。假设您已将所有内容正确连接到周围的过滤器中,那么以下示例可能对您有用:

CurrentUser

希望这会有所帮助!

答案 1 :(得分:0)

我没有提到我需要在每次请求后清除用户。

这是我想出的。将期望值放入lambda有点疯狂,但确实确保在处理请求之前设置了用户,并在处理请求后将其清除

describe '.set' do
  subject { described_class }

  let(:user) { OpenStruct.new(id: 1) }

  let(:user_expectation) { lambda{ expect(subject.user).to eql user } }

  it 'sets the user prior to the block being processed' do
    subject.set(user) { user_expectation.call }
  end

  context 'after the block has been processed' do
    # This makes sure the user is always cleared after a request
    # even if there is an error and sidekiq will never have access to it.

    before do
      subject.set(user) { lambda{} }
    end

    it 'clears out the user' do
      expect(subject.user).to eql nil
    end
  end
end

答案 2 :(得分:0)

我不确定您打算如何完成此任务,因为您似乎只是想确保在块中设置了user,然后再取消设置。如果是这种情况,则以下应能正常工作

class CurrentUser
  attr_accessor :user
  def set(user)
    self.user = user
    yield
  ensure
    self.user = nil
  end
end

describe '.set' do
  subject { CurrentUser.new }
  let(:user) { OpenStruct.new(id: 1) }
  it 'sets user for the block only' do 
    subject.set(user) do 
      expect(subject.user).to eq(user)
    end 
    expect(subject.user).to be_nil 
  end
end

这将检查在块中(称为收益率)内subject.user等于user,之后subject.user为零。

输出

.set
  sets user for the block only

Finished in 0.03504 seconds (files took 0.14009 seconds to load)
1 example, 0 failures