Remarkable 3.0 is out and it’s… well… remarkable!

14 de abril de 2009  |  English, Open Source, Remarkable  |  5 Comentários  | 

Wow, a major release? Yes, a major release and we have plenty reasons for that. Since me and José Valim were working on it for a couple months, we have quite a list :). So follow up:

1. Remarkable Core

Remarkable is now a framework for rspec matchers. Since Rails matchers are not simple, as Remarkable grew, we saw our matchers full of logic to show messages (description and failure messages) and that some methods could be automatically generated, reducing repetitive work.

Compare the allow_mass_assignment_of matcher in Remarkable 2.x and in Remarkable 3.0. Which one do you prefer? :)

So we built a DSL and called it Remarkable, which with Remarkable ActiveRecord and Remarkable Rails, provides you nice matchers/macros to speed up your tests. To install them, just do:

sudo gem install remarkable_rails

You can also install just remarkable or just remarkable_activerecord. But remarkable_rails brings you the whole packet.

2. I18n

On Rails Summit Latin America, Obie Fernandez talked about the Hash Rocket way and one of the items were that they actually print out the specs and give it to the client. Both me and José work with Rails projects and we couldn’t deliver the same to technical clients, because the output was in english. Well, we scratched our own itch!

This is how an English output would be like:

Example disabled: require age to be set

User
- should require name and email to be set
- should ensure length of name is within 3..40 characters
- should require unique values for email
- should ensure numericality of age allowing only integer values and allowing blank values

In Remarkable, we can have the same results in Portuguese:

Exemplo desativado: exigir presença de idade

Usuário
- deve exigir presença de nome e email
- deve garantir tamanho de nome seja entre 3..40 caracteres
- deve garantir valores únicos para email
- deve aceitar apenas números em idade permitindo somente valores inteiros e permitindo valores nulos

As you have noticed everything gets translated including the class and attributes names. This happens by setting up Remarkable and Rails yml files.

3. Macros

In Remarkable earlier versions, we coded the matcher (validate_presence_of) but most of the time we had to do some tweaks in other to a matcher becomes a macro (should_validate_presence_of). In Remarkable 3.0 it happens transparently.

In other words, if you are using Remarkable 3.0 to build your matchers you have cleaner matchers, I18n support and transparent macros creation.

4. Pending and disabled macros

In Remarkable 2.2, we added the ability to mark macros as disabled:

xshould_validate_uniqueness_of :name

And it would print on your specs output:

Example disabled: require unique values for name

As some people pointed out, Remarkable was still lacking support for pending macros. Pending examples in Rspec would be:

it "should have one manager" do
  pending("create managers resource")
end

it "should validate associated manager" do
  pending("create managers resource")
end

And now in Remarkable, you have the pending group:

pending "create managers resource" do
  should_have_one :manager
  should_validate_associated :manager
end

In both cases a message “PENDING: create managers resources” is appended to matcher description.

5. More options to matchers

In Remarkable 2.2, we started to support ALL Active Record validations with ALL options. And now we extended support for association matchers!

From only :dependent and :through as supported options, now it accepts:

:through, :class_name, :foreign_key, :dependent, :join_table, :uniq, :readonly, :validate, :autosave, :counter_cache, :polymorphic

Besides matchers became much smarter. Whenever :join_table or :through is given as option, it also checks if the given table exists. Whenever :foreign_key or :counter_cache is given, it also checks if the given column exists.

6. Controllers matchers extended

To provide I18n, we ported redirect_to and render_template matchers from rspec-rails. We also added some extra options to respond_with and render template, so you can now do:

render_template 'edit', :layout => 'users'

respond_with 422, :content_type => Mime::XML,
                  :body => /Unprocessable Entitity/

And the route matcher is willing to make your life twice easier. Since it tests params recognitation and routes generation at once, you can cut your routing_specs at least in a half! So the following lines:

route_for(:controller => "companies",
          :action => "show",
          :id => "1").should == "/companies/1"

params_from(:get, "/companies/1").should == { :controller => "companies",
                                              :action => "show",
                                              :id => "1" }

Will become:

route(:get, "/companies/1", :controller => "companies",
                            :action     => "show",
                            :id         => "1")

7. Macro stubs

There is a presentation from José Valim that explains this feature with more details, but it basically makes your controllers specs from this:

describe TasksController do
  def mock_task(stubs={})
    @task ||= mock_model(Task, stubs)
  end

  describe "responding to #POST create" do
    it "exposes a newly created task as @task" do
      Task.should_receive(:new).with({'these' => 'params'}).
      and_return(mock_task(:save => true))‏
      post :create, :task => {:these => 'params'}
      assigns[:task].should equal(mock_task)end

    it "redirects to the created task" do
      Task.stub!(:new).and_return(mock_task(:save => true))‏
      post :create, :task => {}
      response.should redirect_to(task_url(mock_task))end
  end
end

Become this:

describe TasksController do
  mock_models :task

  describe :post => :create, :task => {:these => 'params'} do
    expects :new,  :on => Task, :with => { :these => 'params' }, :returns => mock_task
    expects :save, :on => mock_task, :returns => true

    should_assign_to :task, :with => mock_task
    should_redirect_to { task_url(mock_task) }
  end
end

It aims to improve readability and be more DRY, since you declare your expectations/stubs just once. You can see the whole controller specs in rspec and remarkable way compared here.

It works by eval’ing the expectation/stubs chain and performing the action before each macro is executed. On should_assign_to it evals using expectations (:should_receive), on should_redirect_to it uses stubs (:stub!).

We also want to thank David Chelimsky that gave the nice hint to allow :post => :create inside the describe method and suggested to use mocha syntax. :)

8. Documentation, documentation and documentation

Yes, three times, because each project is very well documented. Browse them:

Remarkable:
http://remarkable.rubyforge.org/core/

Remarkable ActiveRecord:
http://remarkable.rubyforge.org/activerecord/
http://remarkable.rubyforge.org/activerecord/classes/Remarkable/ActiveRecord/Matchers.html (just matchers)

Remarkable Rails:
http://remarkable.rubyforge.org/rails/
http://remarkable.rubyforge.org/rails/classes/Remarkable/ActionController/Matchers.html (just matchers)

9. Volunteers?

Last but definitely not least: we need you!

http://travelpod.files.wordpress.com/2009/02/446px-uncle_sam_pointing_finger.jpg

We created a solid basis for matchers/macros creation. And we want to take it further by hosting even more matchers. So anyone who wants to work on Remarkable Datamapper, Remarkable Sequel, Remarkable Sinatra, please step in! We are waiting for you. :)

And all the others can equally help us by joining the group and posting bugs, matchers, enhancements in bug tracking system.

Só os imaturos não testam

6 de abril de 2009  |  Destaques, Opinião, Remarkable  |  5 Comentários  | 

No sábado passado aconteceu em São Paulo o primeiro evento organizado pelo Guru-SP, o Ruby + Rails no mundo Real 2009. Eu e toda a equipe do Ruby Inside Brasil estivemos presentes no evento. Você pode conferir uma cobertura completa das palestras no site.

Eu tive o privilégio de participar do evento como palestrante. Minha palestra foi voltada para o público iniciante/intermediário, e falei sobre como os testes são importantes para a evolução profissional de um desenvolvedor. Como não consegui entregar os slides antes do evento, eles não foram impressos nas apostilas distribuídas, então segue abaixo via SlideShare a minha apresentação. Logo deve sair os vídeos do evento!

Remarkable now supports all ActiveRecord validations

10 de fevereiro de 2009  |  English, Remarkable  |  2 Comentários  | 

Good times! It has been just one week since I announced Diego Carrion and José Valim as members of the Remarkable core team and we already put some effort into making a new shiny release! We are going to cover what’s new on this Remarkable version, step by step.

1. All ActiveRecord validations are supported with all options

In other words, you can write your spec validation macros the same way as you do in ActiveRecord, without consulting the documentation, without worrying if any validation is supported or not, without checking which options are allowed or not. Check it out:

describe User do
  it { should validate_uniqueness_of(:email) }
  it { should validate_presence_of(:email, :password) }
  it { should validate_confirmation_of( :email, :password) }

  it { should validate_acceptance_of(:terms) }
  it { should validate_inclusion_of(:gender, %w(m f), :message => 'whoa! what are you then?') }
  it { should validate_length_of(:password, :within => 6..20) }
  it { should validate_numericality_of(:age, :greater_than_or_equal_to => 18, :allow_nil => false) }

  it { should allow_mass_assignment_of(:password, :email) }
  it { should not_allow_mass_assignment_of(:salt, :hashed_password) }
end

Or if you prefer:

describe User do
  should_validate_uniqueness_of :email
  should_validate_presence_of :email, :password
  should_validate_confirmation_of :email, :password

  should_validate_acceptance_of :terms
  should_validate_inclusion_of :gender, %w(m f), :message => 'whoa! what are you then?'
  should_validate_length_of :password, :within => 6..20
  should_validate_numericality_of :age, :greater_than_or_equal_to => 18, :allow_nil => false

  should_allow_mass_assignment_of :password, :email
  should_not_allow_mass_assignment_of :salt, :hashed_password
end

We updated the wiki and it’s already reflecting the new macros. But you might ask, what happened with the older ones? The older ones are going to be deprecated and you will see a message while running the tests.

What you might have noticed above is that should_protect_attributes now became should_not_allow_mass_assignment_of. This one was based on Shoulda last changes, so who are porting tests from Shoulda gets everything compatible.

2. Pending macros

We are not just bringing macros to Rspec, we are bringng Rspec to macros! So let’s suppose you are doing some code refactoring and you know some tests will fail while you clean the house, what do you do then?

In Rspec, you can do:

xit { should validate_numericality_of(:age) }

Well, now you can do just the same with macros:

xshould_validate_numericality_of :age

And it’s even better because it shows you a nice message:

Example disabled: should validate numericality of age

Yeah!

3. Full I18n support

You know how validations macros (as validate_presence_of) work? Let’s talk about it a little bit.

When you say that we should validate presence of e-mail, we set the e-mail to nil and save the object. Then we search in all error messages in e-mail, if it has a “can’t be blank” message, your validation is working properly and then the test passes, otherwise, the test fails. The problem is, if you change the error message in your application and do not change on the macro, we will never be able to find the message “can’t be blank” and then the tests will always pass.

This is valid for almost rspec matchers, not only on Remarkable. But what’s new is, if you change the message using the I18n YAML files, we will find the message properly and you don’t have to pass :message in your macros. This is new and we are currently the only one doing this.

But remember, if ever you set the message directly in your models like this:

validates_inclusion_of :gender, %w(m f), :message => 'whoa! what are you then?'

Don’t forget to do the same in your macros:

should_validate_inclusion_of :gender, %w(m f), :message => 'whoa! what are you then?'

Deal?

Conclusion

Remarkable is available on GitHub and to install it, just do on your console:

gem sources -a http://gems.github.com/
sudo gem install "carlosbrando-remarkable"

And then on your RAILS_ROOT/config/environment.rb:

config.gem "carlosbrando-remarkable", :lib => "remarkable", :source => "http://gems.github.com/"

Any doubts? Any bug?

We want to hear you! So you can use the Remarkable google group, our bug tracking system, Github comments, whatever suits you better!

See you there!

Remarkable 2.1.7

2 de fevereiro de 2009  |  Remarkable  |  2 Comentários  | 

Acabou de sair a versão 2.1.7 do Remarkable que conta com algumas novidades.

As macros have_index e have_indices agora contam com a opção :unique que verifica se o índice criado na tabela é único.

it { should have_index([:email, :name]).unique }
# ou
should_have_index [:email, :name], :unique => true

Além disso, com o lançamento da nova versão do RSpec alguns ajustes no projeto foram necessários. Estes ajustes foram feitos e agora o Remarkable deve funcionar perfeitamente após atualizar o RSpec.

Mas a novidade mais importante é a adição de dois novos membros ao core team do projeto:

fc66c82eada8b3869009812a61cf5993jpeg

Diego Carrion: Muito conhecido pelo seu blog MouseOver Studio, e foi o responsável pela atualização do projeto para a nova versão do RSpec.


e837f6b7fd146ab16ed3d663476c063ejpeg José Valim: Um dos responsáveis pelo excelente Pagestacker! Iniciou seu trabalho no Remarkable incluindo novos matchers.


Ambos participam ativamente em vários projetos open-source e formarão comigo um time de desenvolvimento para o Remarkable.

Para atualizar a sua versão do Remarkable execute no terminal:

# Isto só precisa ser executado uma vez
gem sources -a http://gems.github.com

# Para instalar
sudo gem install carlosbrando-remarkable

Um logotipo para o projeto Remarkable!

24 de dezembro de 2008  |  Remarkable  |  Nenhum comentário  | 

Meu amigo Márcio Gasparotto me deu de presente um logotipo para o projeto Remarkable! Veja abaixo:

Agora só falta o site do projeto!

Remarkable 2.0.1 e Atualização do (Comovente) Guia de Ruby do Why

Remarkable 2.0.1 e Atualização do (Comovente) Guia de Ruby do Why

19 de dezembro de 2008  |  Destaques, Meus Livros, Open Source, Remarkable, Ruby  |  8 Comentários  | 

Desde que lancei a primeira versão do Remarkable tenho visto cada vez mais pessoas aderindo ao projeto para criar seus testes com maior rapidez. E com uma quantidade maior de pessoas usando nas mais diversas aplicações é claro que os bugs começaram a aparecer.

A maior parte dos problemas ocorriam por uma falha na arquitetura inicial do Remarkable, o que tornou necessário um refactoring no projeto inteiro para estruturá-lo melhor. Na primeira versão, internamente havia uma separação muito clara entre as duas sintaxes que o projeto oferecia. Com a reestruturação não existe mais esta separação, não importa qual é o seu estilo, RSpec ou Shoulda, internamente você sempre usará o mesmo código para realizar os testes.

Desta forma, acabamos por ganhar muitas macros novas.

Enquanto na versão em RSpec isto já era algo comum:

describe Dog do
  it { should belong_to(:user) }
  it { should_not have_many(:fleas) }
end

Na sintaxe do Shoulda apenas possuíamos macros should_[alguma coisa] e quase nenhuma should_not_[alguma coisa]. Mas agora todas as macros possuem as duas opções, assim:

describe Dog do
  should_belong_to :user
  should_not_have_many :fleas
end

Além disso mais testes foram adicionados para garantir que problemas antigos não voltem para nos assombrar.

Para atualizar o Remarkable, execute no terminal (lembrando que no Windows não precisa usar o sudo):

gem sources -a http://gems.github.com
sudo gem install carlosbrando-remarkable

Ainda falta um logo e um site para o projeto. Alguém se habilita?

O (Comovente) Guia de Ruby do Why

wixl-9

Acabei de atualizar o livro com novas traduções e correções. Devido a minha falta de tempo, acabei demorando para aplicar alguns dos patches que me foram enviados.

Na maioria das vezes, os colaboradores são rápidos demais e várias pessoas corrigem o mesmo texto de formas diferentes, e isto complica um pouco na hora de aceitar uma atualização. Eu tenho de olhar arquivo por arquivo antes de decidir qual será aplicado. Mas isto é bom, porque garante uma maior qualidade à tradução, embora torne o processo um pouco mais lento.

O livro pode ser encontrado na url: http://why.nomedojogo.com. Também existe uma versão para impressão em http://why.nomedojogo.com/print.html.

A processo de tradução já foi finalizado, todo o livro já está em português. Ainda falta ajustar algumas imagens e formatações de texto, mas acredito que se conseguirmos mais colaboradores teremos o livro completo e finalizado até o fim do ano.

Quer ajudar? Comece lendo o livro e quando encontrar algo errado altere aqui.

Twitter Images

Twitter Images

27 de novembro de 2008  |  Open Source, Remarkable  |  Nenhum comentário  |