标签: rspec-rails

Rails json.jbuilder api 与 rspec -> ActionView::MissingTemplate

我有一个 Rails (6.0.0) 项目,其中 api 路由响应与 jbuilder (2.9.1) 放在一起。我在尝试测试控制器时使用 rspec-rails (3.9.0) 遇到错误,但它抛出此错误:

Failure/Error: render :show

     ActionView::MissingTemplate:
       Missing template api/users/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062f50>"
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062ed8>"
         * "#<RSpec::Rails::ViewRendering::EmptyTemplateResolver::ResolverDecorator:0x00007efbf0062e88>"
     # ./app/controllers/api/users_controller.rb:8:in `create'
     # ./spec/controllers/api/users_controller_spec.rb:7:in `block (4 levels) in <top (required)>'
     # -e:1:in `<main>'
Run Code Online (Sandbox Code Playgroud)

控制器/api/user_controller.rb:

def create
  @user = User.new(user_params)
  if @user.save
    login(@user)
    render :show
  else
    render json: @user.errors.full_messages, status: 422
  end
end
Run Code Online (Sandbox Code Playgroud)

视图/api/users/show.json.jbuilder:

json.partial! 'api/users/user', user: @user
Run Code Online (Sandbox Code Playgroud)

路线.rb:

  namespace :api, …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails jbuilder rspec-rails

3
推荐指数
1
解决办法
1330
查看次数

测试控制器与 Rails 6 上的 Rspec 的关系

我无法在控制器问题上使用匿名控制器从规范访问会话或路由路径(root_url)。

这是我的代码

module SecuredConcern
  extend ActiveSupport::Concern

  def logged_in?
    session[:user_info].present?
  end

  def redirect_to_login
    redirect_to login_path unless logged_in?
  end

  def redirect_to_home
    redirect_to root_path if logged_in?
  end
end
Run Code Online (Sandbox Code Playgroud)

和规格

require 'rails_helper'

describe SecuredConcern, type: :controller do
  before do
    class FakesController < ApplicationController
      include SecuredConcern
    end
  end

  after { Object.send :remove_const, :FakesController }
  let(:object) { FakesController.new }
  # let(:session) {create(:session, user_info: '')}

  describe 'logged_in' do
    it "should return false if user is not logged in" do
      expect(object.logged_in?).to eq(false)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是跟踪:

Module::DelegationError:
       ActionController::Metal#session …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails rspec-rails activesupport-concern ruby-on-rails-6

3
推荐指数
1
解决办法
2214
查看次数

如何在 RSpec 测试中发送 RSwag 架构之外的参数?

parameter使用 Ruby on Rails 中的 RSwag 和 RSpec,是否可以通过发送未定义为 a 的参数run_test!

测试示例:

# frozen_string_literal: true

require "swagger_helper"

describe "Resources", type: :request, swagger_doc: "api/resources.json" do
  path "/resources" do
    get "get resources" do
      tags "resources"

      parameter name: "sort[column]",
                in: :query,
                type: :string,
                enum: ["created_at", "updated_at"]
                required: false
      parameter name: "sort[order]",
                in: :query,
                type: :string,
                enum: ["asc", "desc"]
                required: false

      response "422", "Unprocessable Entity" do
        context "with unrecognized param" do
          # define sort[direction] here

          run_test! do |respone|
            expect(json_response["errors"]).to contain_exactly(
              # my …
Run Code Online (Sandbox Code Playgroud)

ruby rspec ruby-on-rails rspec-rails rswag

3
推荐指数
1
解决办法
2219
查看次数

令人困惑的 RSpec 哈希匹配差异

我正在使用 RSpec匹配器来检查哈希是否包含预期值。当哈希的键不匹配时,所有动态(a_string_starting_with等)值都显示为不匹配。当您尝试匹配更大的哈希值时,这尤其会分散您的注意力。我想知道是否有另一种方法来检查哈希值,因此只有真正不匹配的值才会显示在差异中。

这是一个示例,a尽管该值是正确的,但其中 被标记为红色。

it 'matches' do
  actual = {
    a: 'test test',
    b: 1,
    c: 2,
  }

  expect(actual).to match(
    a: a_string_starting_with('test'),
    b: 0,
    c: 2,
  )
end
Run Code Online (Sandbox Code Playgroud)

匹配差异

我想知道我是否应该使用另一个匹配器。或者是否有任何自定义匹配器或宝石?

ruby rspec rspec-rails

3
推荐指数
1
解决办法
1259
查看次数

未定义的方法`mock_model'

我正在尝试将Rspec 1.3.1用于我的rails应用程序,它运行在2.3.8上.我可以用stub_model方法"存根"模型.但是当我打电话时mock_model,事情就出错了,这就是我得到的堆栈跟踪

./spec/models/bucket_spec.rb:32: undefined method `mock_model' for Spec::Rails::Example::ModelExampleGroup::Subclass_2:Class (NoMethodError)
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/example/example_group_methods.rb:188:in `module_eval'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/example/example_group_methods.rb:188:in `subclass'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/example/example_group_methods.rb:55:in `describe'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/example/example_group_factory.rb:31:in `create_example_group'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/dsl/main.rb:28:in `describe'
from ./spec/models/bucket_test.rb:31
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:15:in `load'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:15:in `load_files'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:14:in `each'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:14:in `load_files'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/options.rb:134:in `run_examples'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/lib/spec/runner/command_line.rb:9:in `run'
from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.1/bin/spec:5
from /usr/local/bin/spec:19:in `load'
from /usr/local/bin/spec:19
Run Code Online (Sandbox Code Playgroud)

bucket_spec.rb文件:

  require 'spec_helper'
   describe Bucket, "creation" do
  before(:each) do
    @bucket = stub_model(Bucket, :id => 1, :name => "Below Proficient", :color =>     "green", :min_range => 0, …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails rspec-rails

2
推荐指数
1
解决办法
3388
查看次数

使用RSpec将参数传递给Rails控制器操作中的模拟模型方法

我正在尝试模拟用户模型保存方法以返回false,并模拟控制器在验证失败时将执行的操作.

我的规格如下:

require 'spec_helper'

describe UsersController do
  describe 'POST create_email_user' do
    it 'responds with errors json if saving the model fails' do
      @params = {
        :last_name => 'jones',
        :email => 'asdfasdfasfd@'
      }
      User.stub(:new_email_user) .with(@params) .and_return(@mock_user)

      @mock_user.stub(:save) .and_return(false)

      post :create_email_user, :user => @params, :format => :json

      response.body.should == @mock_user.errors.as_json
      response.status.should == :unprocessable_entity
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

控制器动作如下:

class UsersController < ApplicationController
  def create_email_user
    @user = User.new_email_user(params[:user])
    if @user.save
      # code left out for demo purposes
    else
      render json: @user.errors, status: :unprocessable_entity
    end …
Run Code Online (Sandbox Code Playgroud)

mocking rspec-rails ruby-on-rails-3

2
推荐指数
1
解决办法
6607
查看次数

我应该为模型编写什么样的RSpec测试?

我是Rails和测试的新手,我写了这个模型:

class KeyPerformanceInd < ActiveRecord::Base
  #attr_accessible :name, :organization_id, :target

  include ActiveModel::ForbiddenAttributesProtection

  belongs_to :organization
  has_many  :key_performance_intervals, :foreign_key => 'kpi_id'

  validates :name, presence: true
  validates :target, presence: true
  validates :organization_id, presence: true

end
Run Code Online (Sandbox Code Playgroud)

我的问题是这样的模型,我应该写一些RSpec测试?有这样的事吗?或者有什么可以做的事情?我听说过FactoryGirl,我需要测试这个模型还是用于测试控制器中的东西?

Describe KeyPerformanceInd do
  it {should belong_to(:key_performance_interval)}
end 
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails rspec-rails ruby-on-rails-3.2

2
推荐指数
1
解决办法
136
查看次数

Rspec格式将参数发布到String值

当我发送一个对象json时,里面的所有字段都改为字符串,在控制器中断开我的验证,我得到以下错误.

Api::V1::BillsController POST #create when logged in 
     Failure/Error: post :create, { bill: bill_attributes }
     Apipie::ParamInvalid:
       Invalid parameter 'value' value "41.64794235693306": Must be Float
     # ./app/controllers/concerns/exception_aspects.rb:4:in exception_wrapper
     # ./spec/controllers/api/v1/bills_controller_spec.rb:135:in block (4 levels) in <top (required)>
Run Code Online (Sandbox Code Playgroud)

我尝试的测试表明 request.headers['Content-Type'] = 'application/json'

let(:bill_attributes) { FactoryGirl.attributes_for :bill }

before(:each) do
   request.headers['Content-Type'] = 'application/json'
   post :create, { bill: bill_attributes }
end

it "when is valid description" do
    expect(json_response[:description]).to eq(bill_attributes[:description])
end
Run Code Online (Sandbox Code Playgroud)

我的工厂是

FactoryGirl.define do
 factory :bill do
  description { FFaker::Lorem.phrase }
  value { (rand() * 100).to_f } …
Run Code Online (Sandbox Code Playgroud)

ruby rspec ruby-on-rails rspec2 rspec-rails

2
推荐指数
2
解决办法
2131
查看次数

RSpec:设置请求标头

我想ActionDispatch request在我的规范中用helper方法设置重要的标题:

RSpec.describe API::V1::FoosController, type: :request do
  describe 'GET #index' do
    context 'common case' do
      request.env.merge!({'HTTP_FOO': 'FOO'})
      get api_foos_path, {}, {Accept: Mime::JSON}
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是request当涉及到控制器时,这个标题(通常是任何标题集)都会消失:

class API::V1::FoosController < ApplicationController
  respond_to :json, :xml

  def index
    request.env.has_key? 'HTTP_FOO' # false
    respond_with serialize_models(Foo.all)
  end
  # ...
end
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?如何正确设置?设置标题request.header@request.header使用相同的标题.

PS:我知道我可以将标题设置为Rack::Test::Methods助手的第三个参数,但我不想违反DRY - 我只想在那里定义Mime格式.

ruby rspec ruby-on-rails rspec-rails

2
推荐指数
1
解决办法
2364
查看次数

如何在RSpec测试中为JSON API传递身份验证令牌?

我正在尝试get在Rails中向RSpec JSON API测试添加授权令牌.但到目前为止所尝试的一切都会导致错误.问题似乎是令牌未在请求中正确传递.

expected the response to have a success status code (2xx) but it was 401
Run Code Online (Sandbox Code Playgroud)

当前代码:

Project_spec.rb(测试)

before do
    @project = create(:project, :key => "123")
    get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json
end

it "returns correct status" do
    expect( response ).to have_http_status(:success)
end
Run Code Online (Sandbox Code Playgroud)

ProjectsController.rb

before_filter :restrict_access, :except => :create

def show
    @project = Project.find(params[:id])
    render json: @project
end

def restrict_access
    authenticate_or_request_with_http_token do |token, options|
        Project.exists?(key: token)
    end
end
Run Code Online (Sandbox Code Playgroud)

根据网上发现的一些推荐解决方案,我试过了

  1. get '/api/v1/projects/1', format: :json, token: "123" …

json ruby-on-rails rspec-rails

2
推荐指数
2
解决办法
4011
查看次数