17

I am testing my controller action for practice. In my controller, I just want to get all the distinct products by name from my database:

  def shop
    @products = Product.select('distinct on (name) *').sort_by &:order
  end

I've checked this manually and it works fine. Now I am setting up my test using my RSpec and I want to test that @products is an array greater than 0:

RSpec.describe PagesController, type: :controller do
  describe 'GET #shop' do
    it 'should get all proudcts' do
      get :shop
      expect(assigns(:products).count).to be > 0 
    end
  end
end

Now, I've tried several different combinations of the expect... but it keeps telling me that its either nil or 0, which I know it's not. How can I test that an array is greater 0?

2 Answers 2

23

Try

expect(assigns(:products)).to_not be_empty

This works because the array responds to empty?. Another way could be

expect(assigns(:products).count).to be_positive

Because integers respond to positive?

While if you wanted to check an actual count

expect(assigns(:products).count).to eq 1
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively to these options, you can create your own matcher. Here is an example. gist.github.com/danielwestendorf/…
Thanks Ursus. I actually found the problem. I didn't seed my test database with data so I had it right, just didn't set everything up right. smh.
4

You could also turn it around a bit into the following:

expect(assigns(:products)).to have_attributes(count: be_positive)

This allows you to use subject, like this for example:

subject { assigns(:products) }

it { is_expected.to have_attributes(count: be_positive) }

1 Comment

better answer, because array/object content is shown in exception using this approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.