简体   繁体   中英

New Rspec 3 way to stub model (Rails 4.2/Rspec 3.1)

On one Rspec test (which works fine), I have a deprecation warning

Using stub from rspec-mocks' old :should syntax without explicitly enabling the syntax is deprecated. Use the new :expect syntax or explicitly enable :should instead.

How should I change this test to be compliant with Rspec 3?

I am testing that the field company name exists/is not empty, then I have to validate presence of the company phone number field. I used to use 'stub' but it does not work properly and I'd like to move to the new Rspec 3 way.

/spec/models/company_spec.rb

describe "test on company name" do
  context "test" do
    before { subject.stub(:company_name?) { true } }
    it { is_expected.to validate_presence_of(:company_phone_number) }
  end 
end

To stub a method under RSpec 3 use allow/receive :

allow(subject).to receive(:company_name?).and_return(true)

If you would to set an expectation that will fail if company_name? is never called:

expect(subject).to receive(:company_name?).and_return(true)

It could be like this:

describe "test on company name" do

  context "test" do
    before { allow(subject).to receive(:company_name?).and_return(true) }

    ...
  end 
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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