简体   繁体   English

Rspec模拟和返回值

[英]Rspec Mocking and return value

I'm trying to integrate my application with the Sendgrid api. 我正在尝试将我的应用程序与Sendgrid api集成在一起。 For example, when a user registers add the user's email to Sendgrid. 例如,当用户注册时,将用户的电子邮件添加到Sendgrid。

As of now I have the following tests: 到目前为止,我有以下测试:

context "painter registers" do
      let(:new_painter) {FactoryGirl.build(:painter)}
      it "#add_email_to_sendgrid is called" do
        new_painter.should_receive(:add_email_to_sendgrid)
        new_painter.save
      end
      it "Sendgrid#add_email called and should return true" do
        new_painter.email = "nobody-sendgrid@painterprofessions.com"
        Sendgrid.should_receive(:add_email).with("nobody-sendgrid@painterprofessions.com").and_return(true)
        new_painter.save
      end
    end

In my Painter model I have the following: 在我的Painter模型中,我具有以下内容:

 after_create :add_email_to_sendgrid

def add_email_to_sendgrid
   Sendgrid.add_email(self.email)
  end

lib/sendgrid.rb lib / sendgrid.rb

module Sendgrid
    def self.add_email(email_address)
      return false
    end
end

Everything is working up until the return value of Sendgrid.add_email. 一切正常,直到Sendgrid.add_email的返回值。

I can change the add_email methods return value to anything and the test will still pass. 我可以将add_email方法的返回值更改为任何值,并且测试仍将通过。

Please advise. 请指教。

I guess there is confusion in the way you read: 我想您的阅读方式会有困惑:

Sendgrid.should_receive(:foo).with(args).and_return(bar)

You can actually return whatever you want, this is not an expectation, it's just a convenient way to simulate a service. 您实际上可以返回任何想要的东西,这不是期望,它只是模拟服务的便捷方式。

So: 所以:

  • yes, you can return anything you want. 是的,您可以退货。
  • yes, your spec will pass whatever value is returned since you do not spec anything related to it 是的,您的规格将通过返回的任何值,因为您不指定与之相关的任何值

I guess you expct the fail to fail somehow because the after_create returns false, if so, it's kind of awkward to have a creation depend on an external service. 我猜想您会以某种方式失败,因为after_create返回false,如果是,则创建依赖于外部服务有点尴尬。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM