2014-07-06 14 views
34

W moim projekcie Rails Używam RSpec-mocks użyciu any_instance ale chcę uniknąć tego komunikatu Deprecation:RSpec any_instance deprecation: jak to naprawić?

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

Oto moje specyfikacje:

describe (".create") do 
    it 'should return error when...' do 
    User.any_instance.stub(:save).and_return(false) 
    post :create, user: {name: "foo", surname: "bar"}, format: :json 
    expect(response.status).to eq(422) 
    end 
end 

Oto mój kontroler:

def create 
    @user = User.create(user_params) 
    if @user.save 
     render json: @user, status: :created, location: @user 
    else 
     render json: @user.errors, status: :unprocessable_entity 
    end 
end 

Chciałbym użyć nowy: oczekiwać składni ale nie mogę znaleźć sposobu, aby właściwie go używać.

Używam RSpec 3.0.2.

+0

jaka jest twoja wersja RSpec? –

+0

@ArupRakshit 3.0.2 – Rowandish

Odpowiedz

79

Zastosowanie allow_any_instance_of:

describe (".create") do 
    it 'returns error when...' do 
    allow_any_instance_of(User).to receive(:save).and_return(false) 
    post :create, user: {name: "foo", surname: "bar"}, format: :json 
    expect(response.status).to eq(422) 
    end 
end 
5

jestem w stanie odtworzyć go:

W moim pliku test.rb: - ​​

#!/usr/bin/env ruby 

class Foo 
    def baz 
    11 
    end 
end 

W moim pliku test_spec.rb

require_relative "../test.rb" 

describe Foo do 
    it "invokes #baz" do 
    Foo.any_instance.stub(:baz).and_return(20) 
    expect(subject.baz).to eq(20) 
    end 
end 

Teraz, jeśli biegnę to: -

[email protected]:~/Ruby> rspec 
. 

Deprecation Warnings: 

Using `any_instance` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from /home/arup/Ruby/spec/test_spec.rb:4:in `block (2 levels) in <top (required)>'. 

Teraz znalazłem changelog

allow(Klass.any_instance) i expect(Klass.any_instance) teraz wydrukować ostrzeżenie. Zazwyczaj jest to błąd , a użytkownicy zwykle chcą zamiast tego allow_any_instance_of lub expect_any_instance_of. (Sam Phippena)

zmienić test_spec.rb jak poniżej:

require_relative "../test.rb" 

describe Foo do 
    it "invokes #baz" do 
    expect_any_instance_of(Foo).to receive(:baz).and_return(20) 
    expect(subject.baz).to eq(20) 
    end 
end 

i działa idealnie: -

[email protected]:~/Ruby> rspec 
. 

Finished in 0.01652 seconds (files took 0.74285 seconds to load) 
1 example, 0 failures 
[email protected]:~/Ruby> 
Powiązane problemy