Skip to content

Instantly share code, notes, and snippets.

@natikgadzhi
Created March 4, 2010 13:11
Show Gist options
  • Save natikgadzhi/321685 to your computer and use it in GitHub Desktop.
Save natikgadzhi/321685 to your computer and use it in GitHub Desktop.
#
# Using YML fixtures
#
# spec/fixtures/users.yml
admin:
id: 10
login: administrator
is_admin: true
# *_spec.rb
users(:admin)
#
# Using factories
#
# spec/factories/user.rb
#
# Defining a simple factory for User model
Factory.define(:user) do |u|
u.login { Factory.next :user_login }
end
#
# A bit more complex factory, it uses parent to provide basic attributes and is_admin to mention that the user is an admin.
Factory.define(:admin_user, :parent => :user) do |u|
u.id_admin true
end
#
# an article factory which creates an article.
# It the article model requires author to be set and if you'll not provide it as an attribute when you call Factory.create, the
# object created will be invalid.
Factory.define(:article) do |a|
a.title { Faker::Lorem.sentence }
a.body { Faker::Lorem.paragraphs }
end
#
# More complex factory for the article model,
# It'll create an instance of :user factory object if no author attribute was provided.
Factory.define(:article_with_author) do |a|
a.association { :author, :factory => :user }
end
# *_spec.rb
user = Factory.create(:admin_user, { :login => "custom_login" })
article = Factory.create(:article, :author => user)
article_with_new_user = Factory.create(:article_with_user)
#
# Using RR
#
# stubs #method for the object with this three params. anything stands for... anything!
# As you can see, stub & mock accept a block which is executed when the method is called.
stub(my_object).method(param1, param2, anything) do
run_some_code
"something to return"
end
# Requires the object to commit suicide without a single sound (returning nil =) )
mock(my_object).suicide!(anything)
# stub.proxy / mock.proxy — run the original method and then run the proxy.
# proxy should be provided as a block with one or many arguments which are expected to be returned by the original method.
mock.proxy(my_object).method do |returned_value|
returned_value.downcase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment