问题
I am having some trouble controller testing a rails engine that I created. The issue I am having is I can't seem to get rspec to use main_app routes.
For instance, I am writing the following controller test. The test would pass if it wasn't for the main_app.root_path returning nil.
The code I have in my controller spec is:
context "successful session creation" do
let(:user) {FactoryGirl.create :user}
it 'sets user id session' do
get :create, use_route: :authenticatable, email: user.email, password: 'password'
expect(session[:user_id]).to eq user.id
end
end
end
In my controller I have:
def create
user = Authenticatable::User.find_by(email: params[:email])
if user && user.login(params[:password])
session[:user_id] = user.id
redirect_to main_app.root_path, notice: "You are signed in!"
else
flash[:error] = 'Invalid email or password'
redirect_to authenticatable.sign_in_path
end
end
The rspec failure I get is:
NameError:
undefined local variable or method `main_app' for #<RSpec::ExampleGroups::AuthenticatableSessionsController::GETCreate:0x007f9f583d6f18>
How can I make it so that rspec will use all of the route helpers available to me.
My rails_helper.rb file is as follows:
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'shoulda-matchers'
require 'pry'
require 'database_cleaner'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
Thanks in advance for any help or suggestions.
回答1:
It looks like there are otherswith similar problems ... I didn't have a chance to try this out myself but take a look at.
stack overflow
def main_app
Rails.application.class.routes.url_helpers
end
main_app.root_path
回答2:
just put it directly in you controller test file or in rails helper, just like a separate method
来源:https://stackoverflow.com/questions/25232625/how-to-controller-test-rails-4-engine-redirect-back-to-main-app-routes