I am writing up a rspec test - and for some reason, i am told that the method any_instance is undefined. I am quite surprised, because I have a very similar expectations in one of my controllers rspec files - and it works fine. Any ideas why this could be happening?
require 'spec_helper'
describe Subscriber do
it {should belong_to :user}
describe "send_message should use mobile to send message" do
subscriber = Subscriber.new(:number => "123")
Mobile.any_instance.should_receive(:send_sms).with("123")
subscriber.send_message("hello!")
end
end
Error
/subscriber_spec.rb:9:in `block (2 levels) in <top (required)>':
undefined method `any_instance' for Mobile:Class (NoMethodError)
My rspec version (taken from my gemfile is)
gem "rspec-rails", ">= 2.11.0", :group => [:development, :test]
Thanks!
Really clear: you didn't wrap your test in an it block. That's all.
Related
My attendance_rspec.rb file contains:
require "rails_helper"
RSpec.describe Attendance, type: :model do
it { should have_db_column(:date).of_type(:date) }
end
When I run it from the terminal using rspec spec/models/attendance_spec.rb
It shows the error:
Failures:
1) Attendance
Failure/Error: it { should have_db_column(:date).of_type(:date) }
NoMethodError:
undefined method `of_type' for #<RSpec::Matchers::BuiltIn::Has:0x000055e5c65dd3e0>
# ./spec/models/attendance_spec.rb:4:in `block (2 levels) in <main>'
I already have FactoryBot configured along with database_cleaner and capybara gems. What gem am I missing or any config missing in rails_helper.rb?
I followed this link for setting up Rspec
As NickM pointed out, the have_db_column matcher is provided by the shoulda-matchers gem. Add it to your Gemfile and follow the integration steps to use have_db_column.
First i read other posts of users with similiar problems, but couldnt come along where my mistake is. I wanted to start a test with RSpec on the following file:
dashboard_view_spec.rb:
require 'rails_helper'
RSpec.feature "Dashboard", type: :feature do
before(:each) do
#current_user = User.create!(email: "xyz#xyz.com", password: "xyz123")
sign_in_with(#current_user.email,#current_user.password)
end
#NAV BAR RSPEC TEST
scenario 'Home bar nav link present' do
visit "/"
expect(page).to have_text('Home')
end
scenario 'How it work nav bar link present' do
visit "/"
expect(page).to have_text('How it work')
end
scenario 'Support nav bar link present' do
visit "/"
expect(page).to have_text('Support')
end
end
On rails_helper.rb on the top:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rake'
require 'spec_helper'
require 'rspec/rails'
require 'shoulda/matchers'
require 'capybara/rails'
require 'capybara/rspec'
require 'rspec/retry'
require 'devise'
Error message:
Failure/Error: require File.expand_path('../../config/environment', __FILE__)
NoMethodError:
undefined method `[]' for nil:NilClass
# ./config/initializers/devise.rb:258:in `block in <top (required)>'
# ./config/initializers/devise.rb:5:in `<top (required)>'
# ./config/environment.rb:5:in `<top (required)>'
# ./spec/rails_helper.rb:4:in `require'
# ./spec/rails_helper.rb:4:in `<top (required)>'
# ./spec/views/dashboard_view_spec.rb:1:in `require'
# ./spec/views/dashboard_view_spec.rb:1:in `<top (required)>'
No examples found.
Randomized with seed 14549
Then the command i used on the terminal
bundle exec rspec spec/views/dashboard_view_spec.rb
After watching the documentation of testing with Devise i changed the code in dashboard_view_spec.rb and used to sign_in as a user and got the same error message.
Line 258 of devise.rb
config.omniauth :facebook, Rails.application.secrets.facebook[:key], Rails.application.secrets.facebook[:secret], scope: 'email', info_fields: 'email, name'
In the gemfile
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '~> 2.13'
gem 'selenium-webdriver'
gem 'rspec-rails', '~> 3.8'
gem 'factory_girl_rails'
gem 'faker'
gem 'database_cleaner'
end
and
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
The problem is that you're missing a variable that your devise initializer expects to find, but only missing it in the test environment. (not the development environment)
The stack trace that you provided and line 258 from config/initializers/devise.rb are all that are needed. First, let's look at the stack trace:
NoMethodError:
undefined method `[]' for nil:NilClass
# ./config/initializers/devise.rb:258:in `block in <top (required)>'
# ./config/initializers/devise.rb:5:in `<top (required)>'
# ./config/environment.rb:5:in `<top (required)>'
# ./spec/rails_helper.rb:4:in `require'
# ./spec/rails_helper.rb:4:in `<top (required)>'
# ./spec/views/dashboard_view_spec.rb:1:in `require'
# ./spec/views/dashboard_view_spec.rb:1:in `<top (required)>'
Starting from the bottom up, we can see that the first line of your spec is what's causing the issue. If you follow the stack you'll see that it ends up in config/initializers/devise.rb:258 and is complaining that something making a [] method call isn't getting the expected object type in return, and is instead getting nil in return.
Looking at line 258 you find:
config.omniauth :facebook, Rails.application.secrets.facebook[:key], Rails.application.secrets.facebook[:secret], scope: 'email', info_fields: 'email, name'
So you can see that there are two times that [] is called:
Rails.application.secrets.facebook[:key]
Rails.application.secrets.facebook[:secret]
What is expected is that calling Rails.application.secrets.facebook will return an Enumerable object (like an array or a hash) but instead it is returning nil, and when it attempts to run nil[:key] or nil[:secret] it raises an exception because NilClass is not an Enumerable and does not have a [] method. You can test this yourself in the rails console:
nil[:secret]
=> NoMethodError: undefined method `[]' for nil:NilClass
The solution is to ensure that calling Rails.application.secrets.facebook returns the expected object type. The short answer is to edit config/secrets.yml to ensure that the values you require for the test environment are present.
I haven't worked with devise in a long time, but I assume that you can safely use the same values that you're using for the development environment for the test environment. You can read more about secrets() elsewhere, but the basic template for config/secrets.yml is as follows:
environment:
key: value
For example:
test:
my_secret_key: my_secret_value
It should be fairly straightforward to copy and paste the missing facebook secrets into the test environment. After making the change you can verify it worked:
$ RAILS_ENV=test rails console
Rails.application.secrets.facebook[:key]
=> <your key here>
If that worked, then run your spec with rspec and it should successfully get past line 1. (assuming there are no other bugs or missing secrets)
I had very similar errors. Here's how I solved
Run rspec --backtrace
This could produce a lot of console output. Scroll right to the top, and start reading from the top. It will tell you the file your problem started in, and the line it happened on. Go to that file (and that line), and figure out what's missing.
In my case, it was actually a missing variable in credentials.yml, but cases will vary. Like in the excellent answer by #anothermh, it's basically telling you something is missing, so you have to figure out what's missing and make sure you provide it.
Just got the same error, but when I ran bundle exec rake spec instead of bundle exec rspec it worked.
I have a problem with a very basic Rspec code, the same problem as the question 'undefined method `get' for #'.
But in my case none of the solutions given have worked for me!
I have my Rspec code at '/RailsProject/spec/controllers' and the code is:
require "../spec_helper"
describe "ApiMobile", :type => :controller do
it "Log In" do
get 'apiMobile/v0/logIn/test'
expect(response).to be_success
end
end
As you can see I've followed all the instructions but I still have the problem:
1) ApiMobile Log In
Failure/Error: get 'apiMobile/v0/logIn/test'
NoMethodError:
undefined method `get' for #<RSpec::Core::ExampleGroup::Nested_1:0x000000023b5ec8>
# ./api_mobile_controller_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0.00056 seconds
1 example, 1 failure
I have missed something or similar?
Thanks!
I finally discovered what was happening: Peter Alfvin was right, the fault was the isntallation.
I added at the Gemfile 'gem rspec' and at the command line typed 'rspec --init' after the 'bundle install'. But I also needed to add the gem 'rspec-rails' and type 'rails generate rspec:install'.
Now the get command works (I have another error but I think that is related to routes).
I have a controller spec something like this
describe :bizzaro_controller do
let(:credit_card_account) { FactoryGirl.build :credit_card_account }
it "doesn't blow up with just the stub" do
CreditCardAccount.stub(:new).and_return(credit_card_account)
end
it "doesn't blow up" do
credit_card_account
CreditCardAccount.stub(:new).and_return(credit_card_account)
end
end
Which results in this:
bizzaro_controller
doesn't blow up with just the stub (FAILED - 1)
doesn't blow up
Failures:
1) bizzaro_controller doesn't blow up
Failure/Error: let(:credit_card_account) { FactoryGirl.build :credit_card_account }
NoMethodError:
undefined method `exp_month=' for nil:NilClass
# ./spec/controllers/user/bizzareo_controller_spec.rb:5:in `block (2 levels) in <top (required)>'
# ./spec/controllers/user/bizzareo_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
Finished in 0.23631 seconds
2 examples, 1 failure
My credit card factory looks like this:
FactoryGirl.define do
factory :credit_card_account do
exp_month 10
exp_year 2075
number '3'
end
end
My CreditCardAccount is an empty ActiveRecord::Base model
=> CreditCardAccount(id: integer, exp_month: integer, exp_year: integer, number: string)
Versions
0 HAL:0 work/complex_finance % bundle show rails rspec-rails factory_girl
/home/brundage/.rvm/gems/ruby-2.0.0-p247#complex_finance/gems/rails-4.0.0
/home/brundage/.rvm/gems/ruby-2.0.0-p247#complex_finance/gems/rspec-rails-2.14.0
/home/brundage/.rvm/gems/ruby-2.0.0-p247#complex_finance/gems/factory_girl-4.2.0
This should be working. all points that your test database is not correct.
RAILS_ENV=test rake db:drop db:create will drop and recreate your test database. Then try to run your rspec using the rake command, in order to migrate the database: rake rspec
I was having the same problem, but I think the cause of my problem was different. My solution, however, may perhaps be useful: I used the Fabrication gem (http://www.fabricationgem.org/) instead of FG.
The reason why I was having this problem was because I was trying to have FG create/build an object that was not ActiveRecord, it was only an ActiveModel, and it had to be initialized with arguments.
I didn't see in the Fabricator documentation an example totally like what I needed, but I got it with this syntax:
Fabricator(:my_class) do
on_init do
init_with("Company Name", "Fake second arg")
end
end
My problem was that in model I made a private method called :send (forgot that it is already used in Ruby).
I'm upgrading a Rails 2.3.5 app to Rails 3.0.3. But my integration tests
aren't working. I'm getting this error:
NoMethodError: undefined method `content_type' for nil:NilClass
The line to blame is
assert_select "input#artist.title.unsolved", 1
My test_helper.rb for webrat looks likes this:
require "webrat"
require 'webrat/core/matchers'
include Webrat::Methods
Webrat.configure do |config|
config.mode = :rack
end
I'm using shoulda 2.11.3 and webrat 0.7.3 for the testing. I've read,
that webrat and shoulda are compatible with Rails3.
Anyone an idea how to fix this?
Thanks!
tux
ADDITION:
It seems, that the NoMethodError appears from shoulda, not from Webrat, as mentioned in the title. Here is the trace:
NoMethodError: undefined method `content_type' for nil:NilClass
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/activesupport-3.0.3/lib/active_support/whiny_nil.rb:48:in `method_missing'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/actionpack-3.0.3/lib/action_dispatch/testing/assertions/selector.rb:605:in `response_from_page_or_rjs'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/actionpack-3.0.3/lib/action_dispatch/testing/assertions/selector.rb:213:in `assert_select'
test/integration/user_integration_test.rb:52:in `block (3 levels) in <class:UserIntegrationTest>'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/shoulda-context-1.0.0.beta1/lib/shoulda/context/context.rb:412:in `call'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/shoulda-context-1.0.0.beta1/lib/shoulda/context/context.rb:412:in `block in run_current_setup_blocks'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/shoulda-context-1.0.0.beta1/lib/shoulda/context/context.rb:411:in `each'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/shoulda-context-1.0.0.beta1/lib/shoulda/context/context.rb:411:in `run_current_setup_blocks'
/Users/23tux/.rvm/gems/ruby-1.9.2-p136#rails3/gems/shoulda-context-1.0.0.beta1/lib/shoulda/context/context.rb:393:in `block in create_test_from_should_hash'
And here is the whole block context around the assert_select:
class SongIntegrationTest < ActionController::IntegrationTest
context "a visitor" do
context "solving a song" do
setup do
#song = Song.make
visit song_path(#song)
end
should "have two guess fields" do
assert_select "input#artist.title.unsolved", 1
assert_select "input#title.title.unsolved", 1
end
Maybe the assert_select isn't longer available in Rails 3 with Shoulda.
Hope someone can help me!
thx!
There is a fork of webrat that works with rails3 at https://github.com/joakimk/webrat. At some point it should get pulled into the main branch. rails 2.3 is still very popular at this time.