【问题标题】:Rspec 3 - Testing assign in controller actionRspec 3 - 在控制器操作中测试分配
【发布时间】:2016-08-04 02:29:37
【问题描述】:

目前我的控制器中有以下自定义操作:

def set_active
  current_user.active_meal_plan = @meal_plan
  current_user.save

  respond_with @meal_plan, location: -> { meal_plans_path }
end

控制器操作按预期工作。但是,我对如何使用 Rspec 测试 current_user.active_meal_plan = @meal_plan 部分有点茫然。

这是我的测试的样子:

RSpec.describe MealPlansController, type: :controller do
  let(:user) { FactoryGirl.create(:user, :admin) }

  before :each do
    # Sign in with Devise as an admin user
    @request.env["devise.mapping"] = Devise.mappings[:admin]
    sign_in user

    # Bypass CanCan's authorization
    allow_any_instance_of(CanCan::ControllerResource).to      receive(:load_and_authorize_resource){ nil }
  end

  # ...

  describe "PUT #set_active" do
    let(:meal_plan) { FactoryGirl.create(:meal_plan, user: user) }

    it "assigns the requested meal plan to @meal_plan" do
      put :set_active, id: meal_plan
      expect(assigns(:meal_plan)).to eq(meal_plan)
    end

    it "sets the requested meal plan as the user's active meal plan" do
      put :set_active, id: meal_plan
      expect(assigns(user.active_meal_plan)).to eq(meal_plan)
    end

    it "redirects to the meal plans view" do
      put :set_active, id: meal_plan
      expect(response).to redirect_to meal_plans_path
    end
  end

所有测试都通过了,除了第二个。

这是我的用户模型:

class User < ActiveRecord::Base
  # ..
  has_many :meal_plans, dependent: :destroy
  belongs_to :active_meal_plan, class_name: 'MealPlan'
end

还有我的用户工厂:

FactoryGirl.define do
    factory :user do
        first_name 'John'
        last_name 'Doe'
        address 'San Francisco Bay Area'
        email { Faker::Internet.email }
        password "password"
        password_confirmation "password"
        pricing_plan { FactoryGirl.create(:pricing_plan) }
        active_meal_plan nil
    end

    trait :user do
      after(:create) {|user| user.add_role(:user)}
    end

    trait :admin do
      after(:create) {|user| user.add_role(:admin)}
    end
end

此外,显然assigns 将在 Rails 5 中被弃用。实际上,controller tests will be removed。根据我收集的信息,根据讨论,我似乎不应该测试这些东西....

无论如何,我想让这个测试通过。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 testing rspec rspec-rails


    【解决方案1】:

    helper assigns 实际上会获取 ivar,就像 @meal_plan,但 current_user 不是 ivar,而是一个方法。

    这是我将如何测试它:

    it "sets the requested meal plan as the user's active meal plan" do
      put :set_active, id: meal_plan
      expect(user.reload.active_meal_plan).to eq(meal_plan)
    end
    

    【讨论】:

    • 完美运行!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多