Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert errors_on to RSpec 3 syntax?

I recently upgraded from RSpec 2.99 to RSpec 3. This would be one of my specs:

require 'spec_helper'

  describe User, :type => :model do

    it "is invalid without a password" do
      expect(FactoryGirl.build(:user, :password => nil).errors_on(:password).size).to eq(1)      
    end

  end

end

I already ran the Transpec gem that is supposed to convert most of my specs to RSpec 3 syntax. However, I am still getting this error (and a few others):

 Failure/Error: expect(FactoryGirl.build(:user, :password => nil).errors_on(:password).size).to eq(1)
 NoMethodError:
   undefined method `errors_on' for #<User:0x00000108beaba0>

I tried to re-write the test in a number of different ways but the error won't go away.

Can anybody help?

like image 727
Tintin81 Avatar asked Jun 17 '14 16:06

Tintin81


People also ask

What is Ruby RSpec?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

How do I run RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What is let in Ruby?

Use let to define a memoized helper method. The value will be cached. across multiple calls in the same example but not across examples. Note that let is lazy-evaluated: it is not evaluated until the first time. the method it defines is invoked.


2 Answers

If you don't want to bundle another gem, you can call valid? on the test subject and then access the errors array:

require 'spec_helper'

describe User, type: :model do

  it 'is invalid without a password' do
    user = FactoryGirl.build(:user, password: nil)
    user.valid?
    expect(user.errors[:password].size).to eq(1)
  end

end
like image 61
ghr Avatar answered Sep 21 '22 04:09

ghr


Looks like it exists in rspec-collection_matchers. Also from this issue you can monkey patch it.

like image 32
zishe Avatar answered Sep 25 '22 04:09

zishe