I have a controller create action that creates a new blog post, and runs an additional method if the post saves successfully.
I have a separate factory girl file with the params for the post I want to make. FactoryGirl.create calls the ruby create method, not the create action in my controller.
How can I call the create action from the controller in my RSpec? And how would I send it the params in my factory girl factories.rb file?
posts_controller.rb
def create
#post = Post.new(params[:post])
if #post.save
#post.my_special_method
redirect_to root_path
else
redirect_to new_path
end
end
spec/requests/post_pages_spec.rb
it "should successfully run my special method" do
#post = FactoryGirl.create(:post)
#post.user.different_models.count.should == 1
end
post.rb
def my_special_method
user = self.user
special_post = Post.where("group_id IN (?) AND user_id IN (?)", 1, user.id)
if special_post.count == 10
DifferentModel.create(user_id: user.id, foo_id: foobar.id)
end
end
end
Request specs are integration tests, using something like Capybara to visit pages as a user might and perform actions. You wouldn't test a create action from a request spec at all. You'd visit the new item path, fill in the form, hit the Submit button, and then confirm that an object was created. Take a look at the Railscast on request specs for a great example.
If you want to test the create action, use a controller spec. Incorporating FactoryGirl, that would look like this:
it "creates a post" do
post_attributes = FactoryGirl.attributes_for(:post)
post :create, post: post_attributes
response.should redirect_to(root_path)
Post.last.some_attribute.should == post_attributes[:some_attribute]
# more lines like above, or just remove `:id` from
# `Post.last.attributes` and compare the hashes.
end
it "displays new on create failure" do
post :create, post: { some_attribute: "some value that doesn't save" }
response.should redirect_to(new_post_path)
flash[:error].should include("some error message")
end
These are the only tests you really need related to creation. In your specific example, I'd add a third test (again, controller test) to ensure that the appropriate DifferentModel record is created.
Related
Right now I have a subscriber controller that creates a subscriber but that is not what I want to test. I also have a method in the controller that add 1 to the visit attribute on the Subscriber(I'll post the code) that is the method I want to test but I'm not sure how? I'm new to rails and Rspec so I'm having trouble grasping the concepts. I'll post my test and controller for clarity.
CONTROLLER:
def search
#subscriber = Subscriber.new
end
def visit
#subscriber = Subscriber.find_by_phone_number(params[:phone_number])
if #subscriber
#subscriber.visit =+ 1
#subscriber.save
flash[:notice] = "thanks"
redirect_to subscribers_search_path(:subscriber)
else
render "search"
end
end
TEST
it "adds 1 to the visit attribute" do
sign_in(user)
subscriber = FactoryGirl.create(:subscriber)
visits_before = subscriber.visit
post :create, phone_number: subscriber.phone_number
subscriber.reload
expect(subscriber.visit).to eq(visits_before)
end
ERROR MESSAGE:
As you can see that is the method I want to test. The current test in place does not work but I thought it might help to show what I'm thinking. Hopefully this is enough info, let me know if you want to see anything else?
I think you could do something like this:
it 'adds 1 to the visit attribute' do
# I'm assuming you need this, and you are creating the user before
sign_in(user)
# I'm assuming your factory is correct
subscriber = FactoryGirl.create(:subscriber)
visits_before = subscriber.visit
post :create, subscriber: { phone_number: subscriber.phone_number }
subscriber.reload
expect(subscriber.visit).to eq(visits_before)
end
Since you are checking subscriber.visits you should change Subscriber to subscriber:
expect { post :create, :subscriber => subscriber }.to change(subscriber, :visit).by(1)
visits is a method of an instance, not a class method.
I think you're testing the wrong method. You've already stated that your create action works, so no need to test it here. Unit tests are all about isolating the method under test.
Your test as it is written is testing that post :create does something. If you want to test that your visit method does something, you'd need to do something like this:
describe "#GET visit" do
before { allow(Subscriber).to receive(:find).and_return(subscriber) }
let(:subscriber) { FactoryGirl.create(:subscriber) }
it "adds one to the visit attribute" do
sign_in(user)
expect { get :visit }.to change(subscriber, :visit).by(1)
end
end
I am trying to use Rspec to send a post on my create action, I have simple controller logic. This is an api app, i run my rspec and it returns with a 422 status. I am trying to figure out whether or not my spec is sending information to the controller. These are the controller/specs in question, how do i insert information into the create method. So far all tutorials seem to be using the same syntax as mine. Thanks in advance
Ignore the hardcoded user_id in my factory, still learning factories and fixing dependency ones
#post_controller
def create
if User.exists?(params[:user_id])
#post = Post.new(post_params)
#post.save
render json: #post, status: 200
else
render status: 422
end
end
#spec
it "saves a new post in the database" do
attrs = attributes_for(:post)
post :create, post: attrs
expect(response.status).to eq(200)
end
#factory
FactoryGirl.define do
factory :post do
title "This is a new title"
body "This is the body"
user_id 1
end
Maybe is your user_id in params[:post][:user_id]?
I'm testing to make sure that a created user is assigned to my instance variable #user. I understand what get means, but I'm not sure what to write for the test. I'm returning with an argument error for a bad URI or URL. What's wrong with my test and how do I fix it?
it "checks #user variable assignment for creation" do
p = FactoryGirl.create(:user)
get :users
# I'm confused on what this line above means/does. What does the hash :users refer
#to
assigns[:user].should == [p]
end
The expected URI object or string error refers to get :users and the error is as follows
Failure/Error get :users
ArgumentError:
bad argument: (expected URI object or URI string)
I guess that what you want is
it "checks #user variable assignment for creation" do
p = FactoryGirl.create(:user)
get :show, id: p.id
assigns(:user).should == p
end
The line you were not sure about checks that content of the assigned variable (#user) in the show view of the user p, is equal to the p user you just created more information there
what action are you trying to test? usually, for creation, you need to test that the controller's "create" action creates a user and assigns an #user variable
I would test it this way:
describe 'POST create' do
it 'creates a user' do
params = {:user => {:name => 'xxx', :lastname => 'yyy'}}
User.should_receive(:create).with(params)
post :create
end
it 'assigns the user to an #user instance variable' do
user = mock(:user)
User.stub!(:create => user)
post :create
assigns(:user).should == user
end
end
notice that I stub/mock all user methods, since you are testing a controller you don't have to really create the user, you only test that the controller calls the desired method, the user creation is tested inside the User model spec
also, I made 2 tests (you should test only 1 thing on each it block if possible, first it test that the controller creates a user, then I test that the controller assigns the variable
I'm assuming your controller is something like this:
controller...
def create
#user = User.create(params[:user])
end
which is TOO simple, I guess you have more code and you should test that code too (validations, redirects, flash messages, etc)
I have a test that looks like this:
test "should get create" do
current_user = FactoryGirl.build(:user, email: 'not_saved_email#example.com')
assert_difference('Inquiry.count') do
post :create, FactoryGirl.build(:inquiry)
end
assert_not_nil assigns(:inquiry)
assert_response :redirect
end
That's testing this part of the controller:
def create
#inquiry = Inquiry.new(params[:inquiry])
#inquiry.user_id = current_user.id
if #inquiry.save
flash[:success] = "Inquiry Saved"
redirect_to root_path
else
render 'new'
end
end
and the factory:
FactoryGirl.define do
factory :inquiry do
product_id 2
description 'I have a question about....'
end
end
but I keep getting errors in my tests:
1) Error:
test_should_get_create(InquiriesControllerTest):
RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
What am I doing wrong? I need to set the current_user, and I believe I am in the test, but obviously, that's not working.
You didn't create current_user. It was initialized only in test block.
There are two differents ways to do it:
First, use devise test helpers. Something like that
let(:curr_user) { FactoryGirl.create(:user, ...attrs...) }
sign_in curr_user
devise doc
Second, you can stub current_user method in your controllers for test env
controller.stub(current_user: FactroryGirl.create(:user, ...attrs...))
And you should use FactoryGirld.create(...) instead of FactoryGirl.build(...), because you factory objects have to be persisted.(be saved in db and has id attribute not nil)
There are several things which come to mind:
FactoryGirl.build(:user, ...) returns unsaved instance of a user. I'd suggest to use Factory.create instead of it, because with unsaved instance there's no id and there's no way for (usually session based) current_user getter to load it from database. If you're using Devise, you should "sign in" user after creating it. This includes saving record in DB and putting reference to it into session. See devise wiki
Also, passing ActiveRecord object to create action like this looks weird to me:
post :create, FactoryGirl.build(:inquiry)
Maybe there's some rails magic in play which recognizes your intent, but I'd suggest doing it explicitly:
post :create, :inquiry => FactoryGirl.build(:inquiry).attributes
or better yet, decouple it from factory (DRY and aesthetic principles in test code differ from application code):
post :create, :inquiry => {product_id: '2', description: 'I have a question about....'}
This references product with id = 2, unless your DB doesn't have FK reference constraints, product instance may need to be present in DB before action fires.
I'm trying to spec the controller code:
# ClustersController
def create
# create new cluster
#cluster.user = current_user
# save code
end
I am using Rails 3 / RSpec 2 and I'm fairly new to the TDD flow. I basically want to make sure that the user attribute is assigned during the create action.
To begin with i don't think you should create, update an save the object. You can pass the user to the create method, like this:
Cluster.create(:user => current_user)
And to test this you can do:
describe ClusterController do
describe "POST create" do
it "creates a new cluster" do
lamda do
post :create
end.should change(Cluster, :count).by(1)
end
it "set the current user as the new cluster's user" do
user = mock()
Cluster.should_receive(:create).with(:user => user)
post :create
assign(:cluster).user.should == user
end
end
end
I think that will do.
Hope that help.