I’m running in to problems testing a custom post action in my Rails 3.2.8 application. I think it had something to do with transactional fixtures being set to true but could do with some help diagnosing.
I have this in my spec_helper.rb
config.use_transactional_fixtures = true
And my controller spec looks like this:
require 'spec_helper'
describe Api::V1::NasController do
login_user
describe "GET #nas" do
it "posts to startup as new (state) controller" do
@location = FactoryGirl.create(:location_full)
@location.users << @current_user
nas = FactoryGirl.create(:nas, location_id: @location.id )
nas.update_attributes!(:state => 'initialised')
post :start_up, :token => nas.token, :key => nas.key
response.should be_success
end
end
end
I can see the post happening in my server log however the test fails with:
1) Api::V1::NasController GET #nas posts to startup as new (state) controller
Failure/Error: post :start_up, :token => @nas.token, :key => @nas.key
NoMethodError:
undefined method `slice' for nil:NilClass
# ./app/helpers/nas_helper.rb:26:in `queue'
# ./app/controllers/api/v1/nas_controller.rb:99:in `start_up'
# ./spec/controllers/api/v1/nas_controller_spec.rb:16:in `block (3 levels) in <top (required)>'
I have a before filter in my controller which takes the token and key and gives head unauthorised if it can’t find the Nas.
In this test, the Nas is actually found and it moves into the controller action:
def start_up
@token = params[:token]
@nas = Nas.find_by_token("#{@token}")
if @nas
[ do some stuff ]
....
NasSync.enqueue(@nas)
...
end
It’s failing at NasSync.enqueue(@nas) which in turn calls the following helper method (from a resque worker which I omitted):
def self.queue(nas)
node = Nas.find(nas.id).nasname.slice(0..3)
.....
end
In the ‘real’ world, I can post successfully to this url – it’s just in the test environment that it fails.
node = Nas.find(nas.id).nasname.slice(0..3)
Isn’t finding a Nas to slice.
I can’t figure out why it can’t find the Nas, if it gets so far without failing. If I hardcode the node, the test passes.
Is there a specific reason why the nas isn’t being sent over to the helper??
Any suggestions / help appreciated.
— UPDATE —
I’ve turned off transactional fixtures, sorted the mess that was left and am still stuck with the error:
undefined method `slice' for nil:NilClass
Whilst it wasn’t actually transactional fixtures directly causing the problem, turning them off finally pin pointed the issue. Which was actually a tiny bug in my code.
Life within transactions was easy, straight forward and probably quite blinkered. Things passed, when they probably shouldn’t
Turning them off meant I needed to scrap my messy seeds and create the data as and when I needed it.
Lazy coding leads to headaches and more work.
I also realise now that one should have more faith in their abilities and trust the tests that have been written. In this case, that tiny little bug could have caused some big issues. 3 days well spent.