I'm trying to add tests to an old app I started working on, but I'm failing miserably :(
It's a Rails 2.3.8 app with Rspec 1.3.2 and Rspec-rails 1.3.4.
This is all I have right now on a controller spec:
before(:each) do
#attributes = { ... }
end
it 'should create a notification' do
post 'create', :notification => #attributes
assigns[:notification].should_not be_new_record
end
I spent hours trying to figure out why the #notification variable wasn't being set, and I just found out the response has been 501 Not Implemented all this time...
Of course the controller works fine from a browser, so for the life of me I can't figure out why I'm getting that error.
Any ideas?
Bah, I forgot to clone the test database so some of the attributes I was assigning weren't on the test DB, and thus the error.
I only found out after I remembered log/test.log exists... I'm glad nobody answered first or I'd be even more embarrased :D
Related
In my Dashboard#Index I have this in my controller:
tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
This is my spec:
it "assigns all the nodes that are tagged with the current_user email to local variable 'tagged_nodes'" do
get :index
expect(assigns(:tagged_users)).to eq Node.includes(:user_tags).tagged_with(#user.email)
end
This is the error I am getting:
Failure/Error: expect(assigns(:tagged_users)).to eq Node.includes(:user_tags).tagged_with(#user.email)
expected: #<ActiveRecord::Relation []>
got: nil
(compared using ==)
I suspect it is because of the tagged_with which is a helper method from the gem acts_as_taggable_on
Is that what is indeed causing this error? If so, how do I get around that?
If not, what could be causing that error?
Have you tried to reproduce this problem outside of your tests? If not, I think that's the first logical step.
I'd start by trying to reproduce this issue in the controller itself (ie. in your controller action, sprinkle puts statements or insert a binding.pry if you have the excellent Pry gem). If #tagged_users gets populated properly in the controller action when running the dev site, but doesn't get populated when running a spec with the exact same setup, then consider it an Rspec issue. This boils down to "eliminate as many variables as possible in order to isolate the problem".
My MacBook Pro died recently and I got a new one, restored all my files on it and came back to my rails app that I've been developing for quite some time.
In there somewhere, I'd moved the directory where I kept the app (and the Aptana Studio 3 project, though I'm guessing that's not relevant). The app now runs, but all of my functional tests crash, because it thinks the variable "session" is undefined. Here's a boiled down version of my test case code:
require 'test_helper'
class SkillsControllerTest < ActionController::TestCase
...
test "should not copy when current user does not have write permission" do
session[:user] = users(:existingbob)
assert_no_difference("Skill.count") do
post :create, :campaign_id => 1, :skill_uri => {:campaign_id => 1, :skill_id => 1}
end
assert_redirected_to permissions_path()
end
...
end
I do a lot of this, my application check to see if users have permission for a particular action, and I have a lot of tests to check that it's working right.
After my upheaval, the tests crash with the message:
/blah/blah/blah/skills_controller_test.rb:260:in`<class:SkillsControllerTest>':
undefined local variable or method `session' for SkillsControllerTest:Class (NameError)
This all used to work fine, and from what I can tell from the docs, it's still supposed to work just fine. I think I'm misconfigured somehow, but frankly, I don't even know where to start looking.
What's wrong? Where should I look to see?
I've been faithfully been following along with Rails Tutorial 3 and been loving it but am totally stuck with where I've gone wrong after section 9.3.3. Signin Success -> Current user.
I run the rspec tests rspec/spec but have one failure in my sessions_helper.
For some reason the controller.current_user doesn't == #user and I can't for the life of me figure out where I went wrong or why this doesn't work. I understand where things got to for it to fail but can't work out why.
What's more frustrating to me as I'm starting out with rails is I don't know where to even start trying to debug this or what the debugging process is.
I would be eternally grateful if anyone wanted to take on the challenge of forking this from my github [https://github.com/markstewie/railstut_sampleapp][1] and trying to work out the problem. I would be even more grateful if anyone could explain the process you would go through to debug a problem like this... I'm seriously stumped.
/////////////////// SOLUTION /////////////////////////
Sorry guys, I've just found the problem!!! At last...
in session_helper I had.
def remember_token
cookies.signed(:remember_token) || [nil,nil]
rather than
def remember_token
cookies.signed[:remember_token] || [nil,nil]
This has been by far the hardest section to understand and I still don't fully but at least it's working now.
Thanks for your time!
Mark.
Just been struggling with the same section, here's what I found:
Make sure that in sessions_helper.rb you have both the current_user=(user) method from listing 9.15 and the improved current_user method from listing 9.16
and
I had to modify the signed_in? method in session_helper.rb like this:
def signed_in?
!self.current_user.nil?
end
There is actually a remark about changing current_user to self.current_user in footnote 9.6, though that seems to be related to some other section.
HTH
Cloned your rep, run bundle install, migrated the database und run rake rspec. All your tests pass. Can you show your output?
Edit: This was the output
77:test2 markus$ rake spec
(in /Users/markus/Dropbox/Rails/test2)
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -S bundle exec rspec ./spec/controllers/pages_controller_spec.rb ./spec/controllers/users_controller_spec.rb ./spec/models/user_spec.rb ./spec/requests/layout_links_spec.rb ./spec/requests/users_spec.rb
No DRb server is running. Running in local process instead ...
...................................................
Finished in 3.81 seconds
51 examples, 0 failures
I have generated some scaffolding for my rails app.
I am running the generated tests and they are failing.
for example
test "should create area" do
assert_difference('Area.count') do
post :create, :area => { :name => 'area1' }
end
assert_redirected_to area_path(assigns(:area))
end
This test is failing saying that :
1) Failure:
test_should_create_area(AreasControllerTest)
[/test/functional/areas_controller_test.rb:16]:
"Area.count" didn't change by 1. <3>
expected but was <2>.
There is only one field in the model : name. I am populating this so it cant be because I am failing to populate the only field.
I can run the site and create an area with the name 'area1'. So reality is succeeding, but the test is failing.
I cant ask why its failing, because Im sure theres not enough information here for anyone here to know why. Im just stuck at knowing what avenues to go down to work out why the test is failing. Even putting puts into the code dont print out...
What steps can I take to track this down?
Per the request above, and matching what I was expecting that you'd find when you dug into your logs, you have an authorization that isn't being met in your test.
#request and #response are also useful objects to look at (i.e. puts #response inside your test). I don't know what authentication you are using, but check RAILS_ROOT/lib for authenticated_test_helper, or the /lib, or /test of your authentication gem. You'll find methods for performing a login.
I've been trying to solve a problem for a few weeks now. I am running rspec tests for my Rails app, and they are working fine except for one error that I can't seem get my head around.
I am using MySQL with the InnoDB engine.
I have set config.use_transactional_fixtures = true in spec_helper.rb
I load my test fixtures manually with the command rake spec:db:fixtures:load.
The rspec test is being written for a BackgrounDRb worker, and it is testing that a record can have its state updated (through the state_machine gem).
Here is my problem:
I have a model called Listings. The rspec test calls the update_sold_items method within a file called listing_worker.rb.
This method calls listing.sell for a particular record, which sets the listing record's 'state' column to 'sold'.
So far, this is all working fine, but when the update_sold_items method finishes, my rspec test fails here:
listing = Listing.find_by_listing_id(listing_id)
listing.state.should == "sold"
expected: "sold",
got: "current" (using ==)
I've been trying to track down why the state change is not persisting, but am pretty much lost. Here is the result of some debugging code that I placed in the update_sold_items method during the test:
pp listing.state # => "current"
listing.sell!
listing.save!
pp listing.state # => "sold"
listing.reload
pp listing.state # => "current"
I cannot understand why it saves perfectly fine, but then reverts back to the original record whenever I call reload, or Listing.find etc.
Thanks for reading this, and please ask any questions if I haven't given enough information.
Thanks for your help,
Nathan B
P.S. I don't have a problem creating new records for other classes, and testing those records. It only seems to be a problem when I am updating records that already exist in the database.
I suspect, like nathan, transaction issues. Try putting a Listing.connection.execute("COMMIT") right before your first save call to break the transaction and see what changes. That will break you out of the transaction so any additional rollback calls will be non-effectual.
Additionally, by running a "COMMIT" command, you could pause the test with a debugger and inspect the database from another client to see what's going on.
The other hypothesis, if the transaction experimentation doesn't yield any results, is that perhaps your model really isn't saving to the database. Check your query logs. (Specifically find the update query).
These kind of issues really stink! Good luck!
If you want to investigate what you have in DB while running tests you might find this helpful...
I have a rspec test where I save #user.save and it works like a charm, but then I wanted to see if it's really saved in the DB.
I opened rails console for test environment
rails c test
ran
User.all
and as expected got nothing
I ran my spec that contains:
user_attr_hash = FactoryGirl.attributes_for(:user)
#user = User.new user_attr_hash
#user.save
binding.pry
I thought that stopping the test after save would mean that it's persisted, but that's not the case. It seems that COMMIT on the connection is fired later (I have no idea when:\ )
So, as #Tim Harper suggests, you have to fire that commit yourself in the pry console:
pry(#<RSpec::Core::ExampleGroup::Nested_1>)> User.connection.execute("COMMIT")
Now, if you run User.all in your rails console you should see it ;)