Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 951
Patrick Frey Avatar asked Dec 28 '12 09:12

Patrick Frey


3 Answers

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

assigns(:organizer).errors.empty?.should_not be_true
like image 96
VadimAlekseev Avatar answered Nov 09 '22 11:11

VadimAlekseev


The latest preferred syntax is:

expect(assigns(:organizer).errors.empty?).to_not be_true
like image 29
George Shaw Avatar answered Nov 09 '22 10:11

George Shaw


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
like image 1
Rudy Yazdi Avatar answered Nov 09 '22 09:11

Rudy Yazdi