Patrick Frey
Patrick Frey

Reputation: 795

Rails RSpec: Controller Testing, checking if errors Array of model is filled with entries if new record cannot be created due to validation error

I have a still pretty simple Rails application that I want to develop using BDD with Cucumber and TDD with RSpec. Currently, I am hanging at a test where I want to check that if a new instance of an Organizer (that's the model I have) cannot be created due to a validation error. I would like to check that the errors Array of the object to be created is not empty so that I can be sure that error messages are available for showing them in the view.

require 'spec_helper'

describe OrganizersController do render_views

describe "POST 'create'" do

  describe "with invalid arguments" do
    before(:each) do
      request.env["HTTP_REFERER"] = organizers_new_path
      @organizer_args = { :name => "" }
    end      

    it "should return a non-empty list of errors" do
      post 'create', :organizer => @organizer_args
      @organizer.errors.empty?.should_not be_true
    end
  end
end      

end

I am developing based on Rails 3.2.9 with RSpec 2 and cucumber-rails.

Any suggestions are appreciated. Thanks!

Upvotes: 8

Views: 6432

Answers (3)

Rudy Yazdi
Rudy Yazdi

Reputation: 457

thanks for the answer guys but I'd like to suggest a slightly nicer syntax:

expect(assigns(:organizer).errors).to_not be_empty

(unrelated to the question 👇)

Basically whenever you have a method that ends with ? you'll have the corresponding rspec matcher that starts with be_ e.g.

1.odd? #=> true
expect(1).to be_odd

Upvotes: 1

George Shaw
George Shaw

Reputation: 1781

The latest preferred syntax is:

expect(assigns(:organizer).errors.empty?).to_not be_true

Upvotes: 11

VadimAlekseev
VadimAlekseev

Reputation: 2248

You should use assigns method to get instance variable from controller action:

assigns(:organizer).errors.empty?.should_not be_true

Upvotes: 17

Related Questions