Using machinist instead of fixtures - unit-testing

In my Rails 3 application, I have a User model with the following fields
name: string
email: string
children: has_many association to another model
I'm using machinist 2 to generate mock data, its blueprint looks like
User.blueprint do
name { 'user{sn}' }
email { '{object.name}#domain.com' }
end
And User's Unit Test:
require 'test_helper'
class UserTest < ActiveSupport::TestCase
should have_many( :children )
should validate_uniqueness_of( :email )
should_not allow_value("blah").for(:email)
should_not allow_value("b lah").for(:email)
should allow_value("a#b.com").for(:email)
should allow_value("asdf#asdf.com").for(:email)
end
When I generated the user model, it created a fixture file. My understanding is that when I run rake, Rails uses that fixture file to generate objects used in the tests. Which is not what I want. I want Rails to use machinist's blueprints just a seamlessly as it uses the fixtures file.
Is there a way to do this? Is there some way to tell rails that it needs to use blueprints instead of fixtures?

Add this to config/application.rb:
config.generators do |g|
g.fixture_replacement :machinist
end
You can safely trash the old fixtures folder too, unless you want to keep them obviously!

Related

Routing to Controller in ActiveAdmin 1.0.0

rake routes gives the output
POST /admin/users(.:format) admin/users/new
But where is the new action executed? The /admin/user is the registered resource. There are no actions. However creating a new user through the standard AA form puts my user in the database but which controller is used?
UPDATE:
I want to create a new user using ActiveAdmin with a password and store the hashed password using devise. The new action works in my normal user controller which i test through rails console
#user=User.create(params.permit(:name, :phone, :active, :password_digest
#user.password = Devise.friendly_token
So far i hacked the action in the AA user.rb resource like this:(basically the same statements encapsulated in controller do...)
controller do
def new
#user.password = Devise.friendly_token
#user=User.create(params.permit(:name, :phone, :active, :password_digest
The Issue i have now it that the user gets saved in my db but with an unshashed password.(?)
The live demo and the documentation are a bit short on detailed information or examples on this issue.
ActiveAdmin uses inherited resources gem for the default controller actions. If you want to overwrite the new controller action, you can overwrite it in your activeadmin resource code like so:
ActiveAdmin.register User do
controller do
def new
super #use the default methods and response block
#user.activate! #if you want to add some methods
end
end
end
The ActiveAdmin Gem creates a Admin::UsersController on the fly, based on the configuration of you admin/user.rb

Rails: testing custom classes with RSpec

Yea, I know that this question is silly, newbee and simple, but I still can't figure it out.
I've created a class (in app/minions/ directory) to parse auth hashes from 3rd-party services (like google, twitter, etc.). It looks like this.
class AuthHash
def initialize(hash)
#hash = hash
#provider = hash[:provider]
#uid = hash[:uid]
create_user_hash
end
def create_user_hash
#user_hash = send("parse_hash_from_" << #hash[:provider], #hash)
end
def credentials
{provider: #provider, uid: #uid}
end
def user_hash
#user_hash
end
private
# parse_hash_from_* methods here
end
I've added that directory to the autoload path, so I can use it in my controllers. Now I want to write some tests for it.
I'm using RSpec with FactoryGirl for testing. So I started by adding a factory to spec/factories/ called auth_hashes.rb but I can't define a hash as a field in a factory.
So I moved the declaration to the spec/minions/auth_hash_spec.rb.
require 'spec_helper'
describe AuthHash do
before_each do
auth_hash = AuthHash.new({:provider=>"google_oauth2",:uid=>"123456789",:info=>{:name=>"JohnDoe",:email=>"john#company_name.com",:first_name=>"John",:last_name=>"Doe",:image=>"https://lh3.googleusercontent.com/url/photo.jpg"},:credentials=>{:token=>"token",:refresh_token=>"another_token",:expires_at=>1354920555,:expires=>true},:extra=>{:raw_info=>{:id=>"123456789",:email=>"user#domain.example.com",:verified_email=>true,:name=>"JohnDoe",:given_name=>"John",:family_name=>"Doe",:link=>"https://plus.google.com/123456789",:picture=>"https://lh3.googleusercontent.com/url/photo.jpg",:gender=>"male",:birthday=>"0000-06-25",:locale=>"en",:hd=>"company_name.com"}}})
end
end
But still it does not seem to work.
I know this should be alot simpler then I'm trying to do, but I can't figure it out.
Add something like this to that new spec (spec/minions/auth_hash_spec.rb) file at the top:
require Rails.root.to_s + '/app/minions/myhash.rb'
And then write your tests.

Minitest - test class in Rails 4

I am trying to use Minitest in a fresh Rails 4 install. My understanding is that if I have a class that doesn't inherit from ActiveRecord then I should be able to use Minitest itself, without Rails integration:
#test/models/blog.rb
require "minitest/autorun"
class Blog < Minitest::Unit::TestCase
def setup
#b = Blog.new
end
def test_entries
assert_empty "message", #b.entries
end
#app/models/blog.rb
class Blog
attr_reader :entries
def initialize
#entries = []
end
I run the test with ruby test/models/blog.rb.
My problem comes with the setup method. If I don't include an entry for my blog, the tests fails with the message that there are the wrong number of arguments in setup. If I include an entry in my setup message #b = Blog.new entries: "Twilight", my test fails in the test_entries method because entries is an undefined method.
You have a couple problems. First, you are not requiring "test_helper", which means that rails isn't getting loaded when you run this test, which means that the mechanism rails uses to resolve missing constants isn't loaded. You will either need to require the helper or require the blog file directly. Second, you are overwriting the constant you want to test with the test, which is why you are getting confusing messages. Name the test class BlogTest instead to avoid this.
This is what I think you are trying to do:
require "minitest/autorun"
require "models/blog" # Assuming "app" is in your load path when running the test
#require "test_helper" # Or require this instead if you need to use DB
class BlogTest < Minitest::Unit::TestCase
def setup
#b = Blog.new
end
def test_entries
assert_empty #b.entries, "Blog entries should be empty"
end
end

What assertions/tests are needed in a basic "Save/Submit" model test case?

Can anyone help me with what assertions are required in a basic save method test case in CakePHP 2.0?
I have Product, User and News model, I am looking to write a test case for the submit method in the News model and there are so many ways/things to include I was just wondering what is actually needed and what isn't. I have basic fixtures setup for all models.
The method I'm testing will effectively be this:
class News extends AppModel {
public submit($productId, $userId, $newsData) {
// Logic which checks for user and products existence, saves and returns submitted row
}
}
Test Case
public function testSubmit() {
// Save News
$newsData = array(
'News' => array(
'title' => 'Here is the title of the news',
'body' => 'Here is the news body',
'source' => 'News came from here'
)
);
$news = $this->News->submit('product-1', 'user-1', $newsData);
// Now what?
}
Simply assert that $news is an array, object, that the array is equal to an array you expect... Whatever your method returns, you should know it even before implementing the method (test driven development) and be able to assert the result using one or more than one of the phpunit assert methods.
Like simply $this->assertTrue($news); Check the manual for all the asserts. http://www.phpunit.de/manual/current/en/
Also look at the CakePHP core tests to get an idea of how to do test.
Or look at some open source plugin exmaples like
https://github.com/CakeDC/tags/blob/2.0/Test/Case/Model/TaggedTest.php
or
https://github.com/CakeDC/users/blob/2.0/Test/Case/Model/UserTest.php

Adding validates_uniqueness_of to a model fails functional tests

Trying to make a simple application in rails 3.
If I create a team model with rails g scaffold team name:string && rake db:migrate, then run rake, I get success from the prebuilt tests.
If I simply add validates_uniqueness_of :name to the team model. The functional tests fail with
1) Failure:
test_should_create_team(TeamsControllerTest) [/test/functional/teams_controller_test.rb:20]:
"Team.count" didn't change by 1.
<3> expected but was
<2>.
I modified tests/fixtures/teams.yml to look like this:
one:
name: MyString
two:
name: MyString2
The test still fails.
It can't get much more basic than this; what have I missed?
Fixtures basically represent model instances that are in the database.
If you look at the top of test/functional/teams_controller_test.rb you'll see
setup do
#team = teams(:one)
end
and then in your failing functional test you'll have
post :create, :team => #team.attributes
This is what's happening: you're trying to create a new team with the same attributes as "the team fixture named :one". Since both would have the same name (since they have the exact same attributes), the uniqueness validation is failing.
Try replacing your setup block with this
setup do
#team = teams(:one)
#team.name = 'unique name'
end
Now you'll be creating a new team with the name 'unique name' (which isn't in the database according to the fixtures), and your test will pass.