RSpec - 在调用方法时检查条件?

时间:2012-11-29 07:21:45

标签: ruby rspec

现在我断言一个方法被调用:

代码:

def MyClass
  def send_report
    ...
    Net::SFTP.start(@host, @username, :password => @password) do |sftp|
      ...
    end
    ...
  end
end

测试:

it 'successfully sends file' do
  Net::SFTP.
    should_receive(:start).
    with('bla.com', 'some_username', :password => 'some_password')

  my_class.send_report
end

但是,我还想在调用Net :: SFTP.start时检查给定条件是否为真。我该怎么办呢?

it 'successfully sends file' do
  Net::SFTP.
    should_receive(:start).
    with('bla.com', 'some_username', :password => 'some_password').
    and(<some condition> == true)

  my_class.send_report
end

3 个答案:

答案 0 :(得分:1)

您可以为should_receive提供一个块,该块将在调用该方法时执行:

it 'sends a file with the correct arguments' do
  Net::SFTP.should_receive(:start) do |url, username, options|
    url.should == 'bla.com'
    username.should == 'some_username'
    options[:password].should == 'some_password'
    <some condition>.should be_true
  end

  my_class.send_report
end

答案 1 :(得分:0)

你可以使用期待

it 'successfully sends file' do

Net::SFTP.
    should_receive(:start).
    with('bla.com', 'some_username', :password => 'some_password')

  my_class.send_report
end

it 'should verify the condition also' do
  expect{ Net::SFTP.start(**your params**)  }to change(Thing, :status).from(0).to(1)  
end

答案 2 :(得分:0)

谢谢@rickyrickyrice,你的回答几乎正确。问题是它没有验证传递给Net::SFTP.start的正确参数数量。这是我最终使用的内容:

it 'sends a file with the correct arguments' do
  Net::SFTP.should_receive(:start).with('bla.com', 'some_username', :password => 'some_password') do
    <some condition>.should be_true
  end

  my_class.send_report
end