简体   繁体   English

Rails + Rspec:测试表明变量的值为零,否则控制台表明

[英]Rails + Rspec: Test says value of variable is nil, console says otherwise

I have a test that's failing for a custom non active record class I'm writing: 我有一个针对我正在编写的自定义非活动记录类的测试失败:

test: 测试:

describe "#xml_for_initial_request" do

  it "calls the access_request method" do
    ups_shipping = UpsShipping.new
    ups_shipping.should_receive(:credentials)
    ups_shipping.print_xml
  end


end

console: 安慰:

    Failures:

      1) UpsShipping#xml_for_initial_request calls the access_request method
         Failure/Error: ups_shipping.print_xml
         NoMethodError:
           undefined method `to_xml' for nil:NilClass #<-- FAILURE HERE
         # ./app/models/ups_shipping.rb:14:in `print_xml'
         # ./spec/models/ups_shipping_spec.rb:465:in `block (3 levels) in <top (required)>'

    Finished in 0.45009 seconds
    1 example, 1 failure

This occurs in this model: 在此模型中会发生这种情况:

    require 'net/https'
    require 'uri'

    class UpsShipping
      attr_reader :products, :purchase

      def initialize(options = {})
        @products = options.fetch(:products, [])
        @purchase = options[:purchase]
      end

      def print_xml
        xml = ''
        xml << credentials.to_xml #<-- ERROR OCCURS HERE
        return xml
      end

      def credentials #<-- CREDENTIALS COMES FROM HERE
        {
          "AccessLicenseNumber" => UPS_API["access_key"],
          "UserId" => UPS_API["user_id"],
          "Password" => UPS_API["password"]
          }
      end

....

However, when I try this in the console in the test environment it works: 但是,当我在测试环境中的控制台中尝试此方法时,它将起作用:

    Nets-Mac-Pro:myproject emai$ RAILS_ENV=test bundle exec rails c --sandbox
    /Users/emai/.rvm/gems/ruby-1.9.3-p362@myproject/gems/ruby-debug-ide-0.4.18/lib/ruby-debug-ide/command.rb:27: warning: already initialized constant DEF_OPTIONS
    Loading test environment in sandbox (Rails 3.2.13)
    Any modifications you make will be rolled back on exit
    1.9.3p362 :001 > ups_shipping = UpsShipping.new
     => #<UpsShipping:0x007feb0c974790 @products=[], @purchase=nil> 
    1.9.3p362 :002 > ups_shipping.print_xml
     => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n  <AccessLicenseNumber>xxxxx</AccessLicenseNumber>\n  <UserId>xxxx</UserId>\n  <Password>xxx</Password>\n</hash>\n" 
    1.9.3p362 :003 > ups_shipping.credentials
     => {"AccessLicenseNumber"=>"xxxx", "UserId"=>"xxxx", "Password"=>"xxxx"}

What's the deal??? 这是怎么回事???

should_receive is intercepting the method call and not calling the original and, by default, returning nil . should_receive正在拦截方法调用,而不是调用原始方法,并且默认情况下返回nil Add a call to and_call_original : 将通话添加到and_call_original

ups_shipping.should_receive(:credentials).and_call_original

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

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