Accessing view helper methods from Capybara rquest specs - ruby-on-rails

I've got the view helper method in my application helper:
module ApplicationHelper
def formatted_something(something)
"Hello, #{something}"
end
end
I want to access that method in my request spec:
require "spec_helper"
describe "something" do
include RequestSpecHelper
it "should display blogs list" do
visit something_url
page.should have_content formatted_something(#something.something)
end
end
It couldn't find formatted_something method.

You just need to include the relevant helper module in your describe block, and it will be available in all nested specs:
describe "something" do
include RequestSpecHelper
include ApplicationHelper
...
end

Related

Ruby how to use variables outside of included modules

I'm trying to split my code in RSpec into multiple files so it looks nicer. The current file looks like this.
require 'rails_helper'
RSpec.describe Api::MyController do
let(:var1) {}
let(:var2) {}
it 'should calculate some value' do
expect(var1 + var2).to eq('some value')
end
end
Now this is how it looks after refactoring.
require 'rails_helper'
require_relative './mycontroller/calculation'
RSpec.describe Api::MyController do
let(:var1) {}
let(:var2) {}
include Api::MyController::Calculation
end
And this is how calculation.rb looks like.
module Api::MyController::Calculation
it 'should calculate some value' do
expect(var1 + var2).to eq('some value')
end
end
The problem now is that when it runs, it complains var1 and var2 is not defined.
I believe you are looking for RSpec's shared examples:
# spec/support/shared_examples/a_calculator.rb
RSpec.shared_examples "a calculator" do
it 'should calculate some value' do
expect(x+y).to eq(result)
end
end
You then include the shared example with any of:
include_examples "name" # include the examples in the current context
it_behaves_like "name" # include the examples in a nested context
it_should_behave_like "name" # include the examples in a nested context
matching metadata # include the examples in the current context
You can pass context to the shared example by passing a block:
require 'rails_helper'
require 'support/shared_examples/a_calculator'
RSpec.describe Api::MyController do
it_should_behave_like "a calculator" do
let(:x){ 1 }
let(:y){ 2 }
let(:result){ 3 }
end
end

Capybara method is unacceptable from the calss undefined method `expect' for #<ArticleForm:0xb5e98bc>

The method "expect" it not accessible when trying to call from a class method. However, it works fine when calling from the feature spec.So basically the last method (i_expect_to_see_article_on_home_page) is not working.
spec/support/ArticleForm.rb
require 'rails_helper'
class ArticleForm
include Capybara::DSL
def visit_home_page
visit('/')
self
end
def create_an_article
click_on('New Article')
fill_in('Title', with: "My title")
fill_in('Content', with: "My content")
click_on('Create Article')
self
end
def i_expect_to_see_article_on_home_page
visit('/')
expect(page).to have_text("My title")
expect(page).to have_text("My content")
self
end
end
spec/features/article_spec.rb
require 'rails_helper'
require_relative '../support/ArticelForm.rb'
feature "home page" do
article_form = ArticleForm.new
scenario "Visit the home page and post an article" do
article_form.visit_home_page.create_an_article
article_form.visit_home_page.i_expect_to_see_article_on_home_page
end
end
You need to include RSpec::Matchers in your object. You will probably also need to do the same with Capybara::RSpecMatchers if you want to use the capybara matchers
Im not familiar with the syntax you're using but I believe you need to wrap it into "it block".This is how I normally write it:
describe "i_expect_to_see_article_on_home_page" do
it 'should do something' do
visit('/')
expect(page).to have_text("My title")
expect(page).to have_text("My content")
end
end

Adding helper module to Rspec

I would like to add a module that includes a method to help me log in as a user. Here it is:
module TestHelper
require 'spec_helper'
ALL_USERS = ["administrator", "instructor", "regular_user"]
def self.login_as(user_type)
user = User.find_by(global_role_id: GlobalRole.send(user_type))
#request.env["devise.mapping"] = Devise.mappings[:user]
sign_in user
end
end
The spec that's calling it is
require 'spec_helper'
RSpec.describe QuestionsController, :type => :controller do
include Devise::TestHelpers
include TestHelper
describe "a test" do
it "works!" do
TestHelper.login_as("administrator")
end
end
end
And here is the spec_helper
RSpec.configure do |config|
config.include TestHelper, :type => :controller
The error I get is: undefined method 'env' for nil:NilClass It looks like my module doesn't have access to #request.
My question is: how do I access and #request in the external Module?
In addition to the other answers, you should consider only including this module for relevant spec types using the following code:
config.include TestHelper, type: :controller # Or whatever spec type(s) you're using
You could pass #request in to TestHelper.login_as from the tests. Eg
module TestHelper
def self.login_as(user_type, request)
...
request.env['devise.mapping'] = Devise.mappings[:user]
...
end
end
...
describe 'log in' do
it 'works!' do
TestHelper.login_as('administrator', #request)
end
end
But probably better to follow the macro pattern from the devise wiki if other devise mappings in play.

Testing Rails helper with Rspec: undefined local variable or method `request'

I have a helper method that uses 'request' to determine the URL. However, rspec can't seem to find request. I thought request was available to all front-facing tests?
How can I account for the request method in my spec?
Helper Spec
require 'spec_helper'
describe ApplicationHelper do
describe "full_title" do
it "should include the page title" do
expect(full_title("help")).to include('help')
end
end
end
Helper methods
def full_title(page_title)
if staging? # causing the issue
base_title = "Staging"
else
base_title = "Company Name"
end
if page_title.empty?
"#{base_title} | Tag line "
else
"#{base_title} | #{page_title} "
end
end
def staging? # the request here seems to be the problem
request.original_url.include? "staging"
end
Rspec error
Failure/Error: expect(full_title("help")).to include('help')
NameError:
undefined local variable or method `request' for #<RSpec::ExampleGroups::ApplicationHelper_2::FullTitle:0x00000106260078>
Thanks in advance.
First off: request is only available in the controller tests (and even then only in the request specs I think), helper tests are really basic and isolated. Which is good. Your helper code should be really minimal and normally only work on the input it receives.
However this is pretty easily solvable by using stubbing.
So write something like
#note, OP needed to replace 'helper' with 'self'for Rails 4.0.0 and Rspec 3.0
require 'rails_helper'
describe ApplicationHelper do
describe "full_title" do
context "in staging" do
it "should include the page title" do
helper.should_receive(:staging?).and_return(true)
expect(full_title("help")).to include('help')
end
end
context "not in staging" do
it "should include the page title" do
helper.should_receive(:staging?).and_return(false)
expect(full_title("help")).to include('help')
end
end
end
end
Which is imho a very clear, and then you write separate tests for your staging? method:
describe "staging?" do
context "when in staging" do
it "returns true" do
helper.stub(:request) { OpenStruct.new(original_url: 'staging') }
expect( helper.staging? ).to be true
end
end
context "when not in staging" do
it "returns false" do
helper.stub(:request) { OpenStruct.new(original_url: 'development') }
expect(helper.staging?).to be false
end
end
end
end
Some small remarks: ruby default indentation is 2 spaces.
Secondly, your function now literally says return true if true, ideally it should be written like
def staging?
request.original_url.include? "staging"
end

RSpec - How to create helper method available to tests that will automatically embed "it" tests

I am new to ruby/rails/rspec etc.
Using rspec 2.13.1, I want to create a module with a method that can be called from my tests resulting to subsequent calls of the "it" method of the RSpec::Core::ExampleGroup.
My module:
require 'spec_helper'
module TestHelper
def invalid_without(symbols)
symbols = symbols.is_a?(Array) ? symbols : [symbols]
symbols.each do |symbol|
it "should not be valid without #{symbol.to_s.humanize}" do
# Gonna nullify the subject's 'symbol' attribute here
# and expect to have error on it
end
end
end
end
The code above was added to:
spec/support/test_helper.rb
and in my spec_helper.rb, in the RSpec.configure block, I added the following:
config.include TestHelper
Now, in a test, I do the following:
describe Foo
context "when invalid" do
invalid_without [:name, :surname]
end
end
Running this, I get:
undefined method `invalid_without' for #<Class:0x007fdaf1821030> (NoMethodError)
Any help appreciated..
Use shared example group.
shared_examples_for "a valid array" do |symbols|
symbols = symbols.is_a?(Array) ? symbols : [symbols]
symbols.each do |symbol|
it "should not be valid without #{symbol.to_s.humanize}" do
# Gonna nullify the subject's 'symbol' attribute here
# and expect to have error on it
end
end
end
describe Foo do
it_should_behave_like "a valid array", [:name, :surname]
end

Resources