how can i always focus to page using capybara - ruby

I am working on testing rspec and using capybara for interact with form.
I have a problem when i run my file spec if i not focus to page i couldn't submit the form and got the 400 error code so how can focus to page when fill_in text box or click button.
here is the error code
"status": 400,
"result": {
"error": "Grabbing app data from app store failed. Please try again."
}
here is my code interact with form
select_visible(#state, "form label[for='state']+div.field a.chosen-single")
select_visible(#platform, "form label[for='platform']+div.field a.chosen-single")
if #appstore_search != nil && #appstore_search != ""
page.find("#autocomplete_chosen a").click
page.find("#autocomplete_chosen div.chosen-drop div.chosen-search input[type='text']").set(#appstore_search)
if page.has_css?("#autocomplete_chosen ul.chosen-results li.active-result")
page.find("#autocomplete_chosen ul.chosen-results li:nth-child(3)").click
else
fill_in('name', :with => #appstore_search)
end
else
fill_in('name', :with => #name)
end
click_button 'Save'
if page.find("form label[for='platform']+div")[:class].include?("field invalid")
#warning_platform = page.find("form label[for='platform']+div.field.invalid aside.error-message").text
puts #warning_platform
end
if page.find("form label[for='name']+div")[:class].include?("field invalid")
#warning_name = page.find("form label[for='name']+div.field.invalid aside.error-message").text
puts #warning_name
end
if page.has_css?('#alerts ul li')
#message = page.find("#alerts ul li").text
puts #message
end
Please help me fix this problem or suggest me other solution.

Related

Rspec is different from the app

I'm currently working on a Ruby/Sinatra App and now I'm stuck because my rspec testing is not working properly on the controller. But when I tried my API using curl or web the code just works!.
Here are my file, spesificly on that line of code
listproduct_controller.rb
get '/' do
products = Product.all
payload = []
products.each do |product|
payload.push({ :exhibit_name => product.exhibit_name, :icon => product.icon })
end
return {
:status => 'SUCCESS',
:message => 200,
:payload => payload
}.to_json
end
and here are my spec file
listproduct_controller_spec.rb
context "GET to /products" do
before { allow(Product).to receive(:all) }
before { allow(Product).to receive(:find_by) }
it "returns status 200 OK" do
get '/'
puts(last_response)
expect(last_response).to be_ok
end
it "show a list of product's name and its icon" do
get '/'
#products = Product.all.to_a
expect(last_response.body).to include_json(#products)
end
end
When I puts the last_response on spec it shows this
500
{"Content-Type"=>"text/html", "Content-Length"=>"212150"}
#<Rack::BodyProxy:0x0000000480b1d8>
but when im using curl or apps it just works and return
200 status code with the payload
Can anyone help me what I did wrong?
UPDATE :
I solved it, it was the problem on the database, where all the product in the development database were not on the test database so it returns 500 of empty database.

How to include shared examples without subject

I am using RSpec and Capybara. I want to test navigation panel with click_link with shared examples for concrete pages. But I can't use it_should_behave_like because I don't want to change subject after clicking links. Is there any way to include a shared example with expect(page).to?
EDIT:
Here is my code:
require 'spec_helper'
describe "SomeController" do
subject { page }
content_list = {
home: 'Some text on the home page',
about: 'Some text on the about page',
order: 'Some text on the order page'
}
shared_examples_for 'with layout' do
it { should have_content 'Some text on the layout' }
it { should have_title 'Title' }
end
describe 'Home page' do
before { visit root_path }
it_should_behave_like 'with layout'
it { should have_content content_list[:home] }
end
describe 'About page' do
before { visit about_path }
it_should_behave_like 'with layout'
it { should have_content content_list[:about] }
end
describe 'Order page' do
before { visit order_path }
it_should_behave_like 'with layout'
it { should have_content content_list[:order] }
end
it 'should have correct links on the layout' do
visit root_path
click_link 'Some link text'
expect(page).to have_content content_list[:about]
find('.logoLink').click
expect(page).to have_content content_list[:home]
click_link 'Another link text'
expect(page).to have_content content_list[:about]
click_link 'One more link text'
expect(page).to have_content content_list[:order]
end
end
I am checking the same things when visiting pages with route names and when visiting them clicking. I wanted to refactor it.
it_should_behave_like doesn't implicitly change the subject, so you shouldn't have a problem per se.
For example, the following passes:
shared_examples "so" do
it "should have access to variables from calling rspec scope" do
expect(subject).to eql("foo")
expect(page).to eql("bar")
end
end
describe "so test" do
let(:subject) {"foo"}
let(:page) {"bar"}
it_should_behave_like "so"
end
Given the code you shared, it's possible to reduce some duplication by passing a parameter to the shared example you have and introducing variables for each page's content. You can also make use of a lambda function to reduce duplication in the big, sequential example you have at the end. These techniques are shown below (not tested):
require 'spec_helper'
describe "SomeController" do
subject { page }
content_list = {
home: 'Some text on the home page',
about: 'Some text on the about page',
order: 'Some text on the order page'
}
home_content = content_list[:home]
about_content = content_list[:about]
order_content = content_list[:order]
shared_examples_for 'with layout' do |content|
it { should have_content 'Some text on the layout' }
it { should have_title 'Title' }
it { should have_content content }
end
describe 'Home page' do
before { visit root_path }
it_should_behave_like 'with layout', home_content
end
describe 'About page' do
before { visit about_path }
it_should_behave_like 'with layout', about_content
end
describe 'Order page' do
before { visit order_path }
it_should_behave_like 'with layout', order_content
end
it 'should have correct links on the layout' do
click_and_expect = lambda do |link_text, content|
click_link link_text
expect(page).to have_content content
end
visit root_path
click_and_expect['Some link text', about_content]
find('.logoLink').click
expect(page).to have_content home_content
click_and_expect['Another link text', about_content]
click_and_expect['One more link text', order_content]
end
end
However, to respond to one of your comments, I don't know how to easily eliminate the conceptual duplication between the should have_content content in the shared example and the expect(page).to have_content content in the final example. You can replace the former code with the latter code, since page is defined in both cases, but that still leaves you with the duplication of that string.
If you're willing to break up the sequential example at the end into a series of independent examples, then you can use a shared example across both. As is, though, the only way I know to share that code is through an eval of the same string.

Rspec: click_link in email body

I have feature spec test:
describe "Reset password" do
let(:last_email) { ActionMailer::Base.deliveries.last }
it "should be success" do
# ...
page.should have_content t("users.passwords.sent")
last_email.to.first.should eq user.email
last_email.body.should have_content t("mail.body.recovery_instructions")
# Here is click_link
page.should have_content t("passwords.updated")
end
end
How I can click link which is located in last_email.body ?
You can try something like this:
link = last_email.body.raw_source.match(/href="(?<url>.+?)">/)[:url]
visit link

wrong redirect with capybara

I have problem in my previous question, me helped, but and now I've took new.
I'm make integration tests with rspec and capybara.
this my profiles_controllers.rb :
before_filter :authenticate_user!
def update
#profile = current_user.profile
if #profile.update_attributes(params[:profile])
flash[:success] = "Профиль обновлен!"
redirect_to user_path(current_user)
else
render 'edit'
end
end
it's my test file:
describe "ProfilePages" do
subject { page }
describe "edit" do
let(:user) { FactoryGirl.create(:user) }
let(:profile) { FactoryGirl.create(:profile, user: user) }
before do
login user
visit edit_profile_path(profile)
end
it { should have_selector('h2', text: 'Заполните информацию о себе') }
describe "change information" do
let(:new_city) { "Ulan-Bator" }
let(:new_phone) { 1232442 }
let(:new_gamelevel) { "M2" }
let(:new_aboutme) { "nfsfsdfds" }
let(:submit) { "Сохранить" }
before do
fill_in "Город", with: new_city
fill_in "Телефон", with: new_phone
select new_gamelevel, from: "Уровень игры"
fill_in "О себе", with: new_aboutme
click_button submit
end
specify { profile.reload.city.should == new_city }
specify { profile.reload.phone.should == new_phone }
specify { profile.reload.gamelevel.should == new_gamelevel }
specify { profile.reload.aboutme.should == new_aboutme }
end
describe "submitting to the update action" do
before { put profile_path(profile) }
specify { response.should redirect_to(user_path(user)) }
end
end
end
And I have error:
Failure/Error: specify { response.should redirect_to(user_path(user)) }
Expected response to be a redirect to http://www.example.com/users/1 but was a redirect to http://www.example.com/users/sign_in
I use Devise and have login helper in spec/support:
def login(user)
page.driver.post user_session_path, 'user[email]' => user.email, 'user[password]' => user.password
end
And config.include Devise::TestHelpers, :type => :controller in spec_helper.rb
I tried use warden helper login_as , but have same error. How I understand it's don't start session, I'am right?
This is nothing to do with your app code, but the test code.
response object is for controller integration tests, and there is no such object in Capybara.
Normally you can use page object to check response information. And for path checking, a better approach is current_path or current_url.
So your code will work by:
current_path.should be(user_path(user))

Ruby on Rails 3 Tutorial gravatar_for test error

So I am working through the Ruby on Rails 3 Tutorial. I am currently on section 7.1.3 Testing the User show page using factories.
The code is working and pulls the proper gravatar image however I keep getting an error when running my tests.
Here is the error:
Failure/Error: before { visit user_path(user) }
ActionView::Template::Error:
undefined method `downcase' for nil:NilClass
Here is the code from the show.html.erb file:
<% provide(:title, #user.name) %>
<h1>
<%= gravatar_for #user %>
<%= #user.name %>
</h1>
<%= #user.name %>, <%= #user.email %>
Here is the code from the users_helper.rb file:
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user)
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
Here is the code from factories.rb file:
FactoryGirl.define do
factory :user do
name "Curtis Test"
email "test#gmail.com"
password "foobar"
password_confirmation "foobar"
end
end
Here is the code from the test file user_pages_spec.rb
require 'spec_helper'
describe "User Pages" do
subject { page }
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }
it { should have_selector('h1', text: user.name) }
it { should have_selector('title', text: user.name) }
end
describe "signup page" do
before { visit signup_path }
it { should have_selector('title', text: full_title('Sign Up')) }
end
end
I discovered my problem. It had nothing to do with FactoryGirl. The problem was in my user model (user.rb), the line that was causing the issue was
before_save { |user| user.email = user.email.downcase! }
The bang after the downcase was causing the email address to be saved as nil since the return of the downcase! is nil. Once I removed that and made the line look like the following it worked just fine.
before_save { |user| user.email = user.email.downcase }
The way I found it was to load the rails console in test environment and tried to create a new user. I noticed that everything was fine but the email was null.
In general, you can debug issues such as this one by referring to the Rails Tutorial sample app reference implementation.

Resources