Search code examples
rspecrspec-rails

Using RSpec, is there a way to assert whether a specific attribute of a Model is invalid?


I am new to RSpec and I have a test scenario in which I write:

my_object.should_not be_valid

and it works ok. However, I would like to test whether a particular attribute of the model is not valid. Is such a ready-made RSpec behaviour? Can I write something like:

my_object.should_not be_valid(:name)

Ideally, I would like to be able to test the number of errors too, with something like:

my_object.should_not be_valid(:name => 1)

but this is not that important to me now.


Solution

  • According to this, you should be able to write either like this:

    describe Person do
      it "should validate presence of email" do
        person = Person.new(:email =>; nil)
        person.should_not be_valid
        person.should have(1).error_on(:email)
      end
    end
    

    Or like below, by using these rspec matchers:

    describe Person do
      it { should validate_presence_of(:email) }
    end