0

I'm using Rails 3.2's rake tests function. I'm trying to pass a test but it's giving me errors. Btw, when see you how I write, I'm a noob. It's a hacked way of testing, but at least I want to try passing it first.

  test "product title must have at least 10 characters" do
    ok = %w{ aaaaaaaaaa aaaaaaaaaaa }
    bad = %w{ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa}

    ok.each do |name|
        assert new_product_title(name).valid?, "#{name} shouldn't be invalid"
    end

    bad.each do |name|
        assert new_product_title(name).invalid?, "#{name} shouldn't be valid"
    end
  end

with the function

def new_product_title(title)
    Product.new(title: title,
        description: "yyy",
        price: 1,
        image_url: "fred.gif")
end

somehow it's not passing.

What's the reason here? And is there a better way to write it?

Perception
  • 79,279
  • 19
  • 185
  • 195
user1372829
  • 1,121
  • 1
  • 11
  • 21

1 Answers1

1

I'm more concerned about the method. I'm assuming this method is in a product model? It seems what you are trying to do should definitely be controlled by the model, but I don't think you can call a class's method inside the class's definition. I also don't see much utility in a method that creates a new product with specified title, but static description, price, and image_url. If you need default values for specific attributes, you can set those in an initialize method and overwrite them later if needed. Some people frown on setting defaults in initialize so instead you can set them in an after_initialize callback like this:

class Product < ActiveRecord::Base
  after_initialize :init

  def init
    self.description ||= 'yyy'
    self.price ||= 1
    self.image_url ||= "fred.gif"
  end
end

Then whenever you needed to create a new product with a title and the default attributes you can just use

Product.new(:title => "some title")

And if you don't want all the defaults you can just pass the values into new like usual

Product.new(:title => "some other title", :price => 400) # desc & url are still default

About your tests. I always test in RSpec. Since you are using Test Unit (or Mini Test or whatever it is now), my advice my not be correct. But first I would make the variable names more descriptive. Secondly, there are some commas at the end of your assertions that shouldn't be there.

test "product title must have at least 10 characters" do
  valid_name = "a" * 10
  short_name = "a" * 9

  valid_product = Product.new(:name => valid_name)
  assert valid_product.valid?

  invalid_product = Product.new(:name => short_name)
  assert invalid_product.invalid?
end

If you get that working you may want to verify that the product is invalid for the correct reason using an assert equals method on invalid_product.errors.full_messages and the expected string from the error.

Brandon
  • 616
  • 7
  • 10