After a factory girl create I have the following
it "should display the email of user if public" do
#user.update_attributes(:public_email => true)
# I have also tried
# #user.public_email = true
# and
# #user.toggle!(public_email)
#user.save
puts "EMAIL IS #{#user.public_email}"
get :show, :id => #user.id
response.should have_selector("dt", :content => "Email")
end
Rspec will print that "EMAIL IS true" but in the view, public_email is not true (I have <%= "User email is #{#user.public_email}." %> and that prints false).
All my other tests work as expected and it works fine in development.
Why is this happening?
EDIT:
This is my own fault. I was trying to avoid writing the line get :show, :id => #user.id a bunch of times, so I had another before(:each) do call after those tests, and I thought by listing it after them it would not count, but apparently it does.
Related
I am trying to resolve an issue with my rspec test to create an object but the count doesn't seem to change whatever i try. I am sure i am missing something very basic here.
Here is my rspec:
before do
login_account_admin(user)
#group = Factory(:group, :code => "GR_111", :description => "description for GR_111")
Group.stub!(:find).and_return(#group)
end
describe "#create" do
it "should create a new group object" do
group_params = {:code => "NEW_GROUP", :description => "description for NEW_GROUP"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to change(Group, :count).by(1)
end
it "should not create a new group object with invalid code format" do
group_params = {:code => "invalid", :description => "description for invalid code name group"}
expect {
post :create, :service_id => service, :cdb_group => group_params, :button => "save", :format => "js"
}.to_not change(Group, :count)
end
end
"code" parameter can only contain uppercase letters A to Z, 0-9 and _
Here is the controller method definition for #create
def create
#group = Group.new(params[:cdb_group])
respond_to do |format|
if params[:button] == "cancel"
format.js { render "hide_new"}
elsif #group.save
format.js {
render 'show_new_group'
}
format.html { redirect_to(some_path(#service), :notice => 'Group was successfully created.') }
format.xml { head :ok }
end
end
end
Here is the Group model:
class Group < ActiveRecord::Base
validates_uniqueness_of :code
validates_presence_of :code, :description
validates_format_of :code, :without => /[^A-Z0-9_]/ , :message => 'can only contain uppercase letters A to Z, 0-9 and _'
end
Whenever i try to run the rspec test I get the following errors:-
1) GroupsController User As Account Admin goes to #create should create a new group object
Failure/Error: expect {
count should have been changed by 1, but was changed by 0
# ./spec/controllers/groups_controller_spec.rb:51
2) GroupsController User As Account Admin goes to #create should not create a new group object with invalid code format
Failure/Error: expect {
count should not have changed, but did change from 2 to 1
# ./spec/controllers/groups_controller_spec.rb:58
Any help in this regard would be highly appreciated?
Whenever our tests give us unexpected trouble, it's important to take a step back and re-evaluate our approach. Usually, this is an indication of some design problem, either with the code we're testing or with tests themselves.
While it sounds like using a truncation strategy has fixed this particular problem (see more on that below), i would suggest that there is more to learn from the situation.
Consider the two examples from your spec above. The only difference between them comes down to whether the code parameter is valid or not. I would argue that these examples are really testing the Group model, not the controller.
Now, if we're confident in our model test coverage, then we can take a different approach to the controller spec. From the controller's perspective, the model is a collaborator and in general, we always want to avoid indirectly testing collaborators. In this case, we can use a mock to simulate the behavior of the Group model and only test the controller behavior in isolation.
Something like this (please note the code below is incomplete and untested):
# spec/controllers/groups_controller_spec.rb
describe "#create" do
before do
# use a Test Double instead of a real model
#new_group = double(Group)
#params = { :cdb_group => 'stub_cdb_group_param', :service_id => service }
# using should_receive ensures the controller calls new correctly
Group.should_receive(:new).with(#params[:cdb_group]).and_return(#new_group)
end
context "when cancelled responding to js" do
it "renders hide_new" do
post :create, #params.merge({:button => "cancel", :format => "js"})
expect(response).to render_template('hide_new')
end
end
context "with valid params" do
before do
#new_group.should_receive(:save).and_return(true)
end
context "responding to json" # ...
context "responding to html" # ...
context "responding to xml" #...
end
context "with invalid params" do
before do
#new_group.should_receive(:save).and_return(false)
end
# ...
end
end
While the above doesn't specifically address the problem with record counts you were having, i suspect the problem may go away once you isolate your test targets correctly.
If you choose to stick with database truncation, consider using it selectively as described here.
I hope at least some of that helps :).
After fiddling with my spec_helper.rb file. It turns out that i have to change my database cleaning strategy to truncation. Here is my spec_helper file, for reference (https://gist.github.com/aliibrahim/7152042)
I changed this line in my code and disable use of transactional_fixtures
config.use_transactional_fixtures = false
and my database cleaning strategy is now:
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
This gives a clear database before the start/end of every scenario. Hope this helps anyone!
You should test...
1) Group.create(group_params).should be_true after group_params = ...
If this fails, the problem probably related to model or test environment.
2) response.status.should == 302 after post ...
If this fails, the problem probably related to session (authentication / authorization).
3) assigns(:group).should be_valid after post ...
If this fails, the problem probably related to controller.
I have the following controller RSpec test that should work however when I try to execute the below code:
require 'spec_helper'
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe UsersController do
include Devise::TestHelpers #Include devise test helpers
render_views # Render devise views
describe "GET 'show'"
before(:each) do
#user = User.find(params[:id])
#attr = {:initials => 'EU', :name => 'Example', :full_name => 'Example User',
:email => 'user#example.com', :password => 'password', :password_confirmation => 'password'
##attr = User.all
}
end
it 'should be successful when showing OWN details' do
get :show, :id => #attr
response.should be_success
end
it 'should find the correct user' do
get :show, :id => #attr
assigns(#attr).should == #attr
end
end
However I am getting the following output: Undefined locacl variable or method 'params' for RSPRC I believe this set up should be correct.
I see a few things going on here.
Your calling params within the before statement but where is the id ever set? No where in this code do I see where the user id is ever actually determined/found. You should set #user explicitly using either an id that you know exists or doing something such as User.first.
Then instead of calling
get :show, :id => #attr
you should be calling
get :show, :id => #user.id
Also I'm not sure why you need to include spec_helper twice. Line 2 should be able to be removed.
One more thing - assigns(#attr).should == #attr doesn't make any sense. It should be assigns(:attr).should == #attr. Otherwise you would be passing the value of #attr into the assigns method.
I've been learning Rails 3 with Devise and, so far, seem to have it working quite well. I've got custom session & registration controllers, recaptcha is working and a signed-in user can upload an avatar via carrierwave, which is saved on S3. Pretty happy with my progress.
Now I'm writing Rspec tests. Not going so well! I have a reasonable User model test, but that's because I found it online (https://github.com/RailsApps/rails3-devise-rspec-cucumber/) and was able to add to it by following Michael Hartl's excellent "Ruby on Rails 3 Tutorial".
My real problem is controller test and integration tests, especially controller tests. Initially I thought I'd be able to convert the tests in Michael's book, and I have to a small degree, but it's slow progress and I seem to be constantly hitting my head against a brick wall - partly, I think, because I don't know Rspec and capybara so well (have made some very dumb mistakes) but also because I don't really understand Devise well enough and am wondering if Devise plays as nicely as it might with Rspec; I read somewhere that, because Devise is Rack based, it might not always work as one might expect with Rspec. Don't know if that's true or not?
I know some people will wonder why this might be necessary since Devise is a gem and therefore already tested but I've had a couple of instances where changes elsewhere have broken login or registration without me immediately realizing. I think a good set of controller & integration tests would have solved this.
If I was able to do this myself I would and I'd publish it for others but, so far, writing these tests has been extremely painful and I really need to move on to other things.
I'm sure I wouldn't be the only one who could use this. Anyone know of a such a suite of tests?
In response to Jesse's kind offer of help...
Here is my registrations_controller_spec. The comments in "should render the 'edit' page" show the sort of things I am struggling with. Also, "should create a user" has some things I've tried to test but not been able to:
require File.dirname(__FILE__) + '/../spec_helper'
describe Users::RegistrationsController do
include Devise::TestHelpers
fixtures :all
render_views
before(:each) do
#request.env["devise.mapping"] = Devise.mappings[:user]
end
describe "POST 'create'" do
describe "failure" do
before(:each) do
#attr = { :email => "", :password => "",
:password_confirmation => "", :display_name => "" }
end
it "should not create a user" do
lambda do
post :create, :user_registration => #attr
end.should_not change(User, :count)
end
it "should render the 'new' page" do
post :create, :user_registration => #attr
response.should render_template('new')
end
end
describe "success" do
before(:each) do
#attr = { :email => "user#example.com",
:password => "foobar01", :password_confirmation => "foobar01", :display_name => "New User" }
end
it "should create a user" do
lambda do
post :create, :user => #attr
response.should redirect_to(root_path)
#response.body.should have_selector('h1', :text => "Sample App")
#response.should have_css('h1', :text => "Sample App")
#flash[:success].should == "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
#response.should have_content "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
end.should change(User, :count).by(1)
end
end
end
describe "PUT 'update'" do
before(:each) do
#user = FactoryGirl.create(:user)
#user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
sign_in #user
end
describe "Failure" do
before(:each) do
# The following information is valid except for display_name which is too long (max 20 characters)
#attr = { :email => #user.email, :display_name => "Test", :current_password => #user.password }
end
it "should render the 'edit' page" do
put :update, :id => subject.current_user, :user => #attr
# HAVE PUT THE DEBUGS THAT I'D LIKE TO GET WORKING FIRST
# Would like to be able to debug and check I'm getting the error(s) I'm expecting
puts subject.current_user.errors.messages # doesn't show me the errors
# Would like to be able to debug what html is being returned:
puts page.html # only return the first line of html
# Would like to be able to determine that this test is failing for the right reasons
response.should have_content "Display name is too long (maximum is 20 characters)" # doesn't work
response.should render_template('edit')
end
end
describe "Success" do
it "should change the user's display name" do
#attr = { :email => #user.email, :display_name => "Test", :current_password => #user.password }
put :update, :id => subject.current_user, :user => #attr
subject.current_user.reload
response.should redirect_to(root_path)
subject.current_user.display_name == #attr[:display_name]
end
end
end
describe "authentication of edit/update pages" do
describe "for non-signed-in users" do
before(:each) do
#user = FactoryGirl.create(:user)
end
describe "for non-signed-in users" do
it "should deny access to 'edit'" do
get :edit, :id => #user
response.should redirect_to(new_user_session_path)
end
it "should deny access to 'update'" do
put :update, :id => #user, :user => {}
response.should redirect_to(new_user_session_path)
end
end
end
end
end
Acording to Devise Wiki, controller tests have to be some kind of hibrid (unit + integration) tests. You have to create an instance of User (or you auth entity) in the database. Mocking Devise stuff is really hard, trust me.
Try this: How-To:-Controllers-and-Views-tests-with-Rails-3-and-rspec
With Cucumber, you can create a step that already do the login process.
Hope it helps.
OK, so a couple of things to make this work:
Here's how you should test that the body have specific text (you were missing the .body
response.body.should include "Display name is too long (maximum is 30 characters)"
You could also test that the #user has an error:
assigns[:user].errors[:display_name].should include "is too long (maximum is 30 characters)"
But, you do need to actually make the name be over 20/30 characters long, so I changed the attributes being posted to:
#attr = { :email => #user.email, :display_name => ("t" * 35), :current_password => #user.password }
https://gist.github.com/64151078628663aa7577
using rails 3.1 here. i am having some problems with session variables in my integration test.
test "new registration" do
get "/user/sign_up?type=normal"
assert_response :success
assert_equal 'normal', session[:registration]
assert_template "user_registrations/new"
assert_difference('User.count', +1) do
post "/user", :user => {:email => "kjsdfkjksjdf#sdfsdf.com", :user_name => "lara", :password => "dfdfdfdfdfdf", :password_confirmation => "dfdfdfdfdfdf"}
end
assert_response :redirect
assert_template "user_registrations/new"
#user = User.find_by_user_name('lara')
assert_equal 'lara', #user.user_name
#user.confirm!
end
all of the assertions pass so thats good, but from what i can tell, session[:registration] is not getting passed when post to "/user".
in my create action in the user_registration controller:
if session[:registration] == "normal"
#user.role = "normal"
#user.status = "registering"
#user.save
else
#user.role = "fan"
#user.save
end
So when the user is created, #user.role = "fan", when it should be #user.role = "normal".
I cant seem to get that session variable to pass when i post. from what i understand, in the "new registration" test, all the session variables remain active as long as the test has not ended. am i wrong to assume that that session variable should be posted? any suggestions?
I`m trying to test my controller with rspec and always get an error.
users_controller.rb:
def update
#user.update_attributes!(params[:user])
redirect_to #user, :status => 202, :text => render_to_string(:partial => "users/show", :type => "json", :locals => {:user => #user})
#notice, that redirect_to was reinitialized and :text is a parameter for response_body
end
_show.tokamak
user {
id user.id
email user.email
username user.username
}
spec file
it "should NOT update user username" do
username = #user.username
put 'update', :id => #user.id, :user => {:username => username+"abc"}, :format => :json
response.status.should be(202)
response.headers["Location"].length.should be > 0
puts response.body
#user.reload
#user.username.should eq(username)
end
end
So I get an error:
Failure/Error: put 'update', :id =>
#user.id, :user => {:username =>
username+"abc"}, :format => :json
ActionView::Template::Error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
# C:/Users/makaroni4/free_frog/ffapi/app/views/users/_show.tokamak:1:in
_app_views_users__show_tokamak___509498818
_32151168_368311673'
# C:/Users/makaroni4/XXX/XXX/app/controllers/users_controller.rb:22:in
update'
# ./users_controller_spec.rb:34:in
`block (4 levels) in '
So may be I call render_to_string method wrong?
Try stubbing out find?
mock_user = User.stub(:find).with(#user.id) {#user}
To be honest I'd go a few steps further and make sure you mock and stub most of the relevant behavior of the User object (or whatever class #user is). Keep in mind you're only testing that the controller action returns what you expect if you give it valid input--not that the model itself does the right thing.
I had a lot of difficulty wrapping my head around the differences in model vs. controller specs...
I hope this helps...if not, I apologize in advance...
EDIT:
I'll take this a step futher and suggest this test is actually a model test. The actual controller test would be something like as the way your spec test should behave:
it "should NOT update user with invalid input" do
mock_user = mock_model(User, {}).as_null_object
User.stub(:find).with("12") {mock_user}
User.stub(:update_attributes).with({}).and_return(false)
put 'update', :id => "12"
# test that your output is correct, or even if the render target is what you expect.
end