【问题标题】:Rails trouble with Rspec and Factory GirlRspec 和 Factory Girl 的 Rails 问题
【发布时间】:2012-06-12 12:16:35
【问题描述】:

我正在尝试使用 Rails。这是我的第一个 Rails 应用程序,我正在为我们未来的项目评估过程中对其进行测试。我一直关注 railstutorial.org 到第 9 章,然后尝试自己继续。

使用 Rails 3.2.3、Ruby 1.9.3、Factory Girl 1.4.0 和 rspec 2.10.0。

我遇到的麻烦在于客户--[has_many]-->用户关系。

运行测试时无法通过的错误:

1) User 
     Failure/Error: let(:client) { FactoryGirl.create(:client) }
     NoMethodError:
       undefined method `user' for #<Client:0x000000045cbfa8>

spec/factories.rb

FactoryGirl.define do
  factory :client do
    sequence(:company_name)  { |n| "Company #{n}" }
    sequence(:address) { |n| "#{n} Example Street"}   
    phone "0-123-456-7890"
  end

  factory :user do
    sequence(:name)  { |n| "Person #{n}" }
    sequence(:email) { |n| "person_#{n}@example.com"}   
    password "foobar"
    password_confirmation "foobar"
    client

    factory :admin do
      admin true
    end
  end

spec/models/user_spec.rb

require 'spec_helper'

describe User do

  let(:client) { FactoryGirl.create(:client) }
  before { @user = client.users.build(name: "Example User", 
                        email: "user@example.com", 
                        password: "foobar", 
                        password_confirmation: "foobar") }

  subject { @user }

  it { should respond_to(:name) }
end

app/controllers/clients_controller.rb

class ClientsController < ApplicationController
  def show
    @client = Client.find(params[:id])
  end

  def new
    @client = Client.new
    @client.users.build # Initializes an empty user to be used on new form
  end

  def create
    @client = Client.new(params[:client])
    if @client.save
      flash[:success] = "Welcome!"
      redirect_to @client
    else
      render 'new'
    end
  end
end

app/controllers/users_controller.rb

class UsersController < ApplicationController
  .
  .
  .

  def new
     @user = User.new
  end

  .
  .
  .
end

app/models/user.rb

class User < ActiveRecord::Base
  belongs_to :client

  .
  .
  .
end

app/models/client.rb

class Client < ActiveRecord::Base 
  has_many :users, dependent: :destroy
  .
  .
  .

end

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot


    【解决方案1】:

    在您的 user_spec 中,您调用的是 client.users,但在其他地方显示客户端属于用户(单数)。如果是这样,请尝试以下操作:

    FactoryGirl.define do
      factory :client do
        ...
        association :user
      end
    end
    
    describe User do
       let(:user) { FactoryGirl( ... ) }
       let(:client) { FactoryGirl(:client, :user => user) }
       subject { user }
       it { should respond_to(:name) }
    end
    

    【讨论】:

    • 其实用户应该属于客户端,客户端有很多用户。我将用我的模型更新问题。也许我以某种方式搞砸了那里的关联......
    • 谢谢@Mori。我已经更新了我的模型。我不确定您的解决方案是否仍然适用。我真的希望关系是客户--[has_many]-->user,因此,用户--[belongs_to]-->client
    • 原来模型中有一条被遗忘的行确实重新定义了客户端中的 :user 属性。谢谢。
    猜你喜欢
    • 2014-01-12
    • 2015-11-14
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2011-07-28
    • 2011-06-03
    相关资源
    最近更新 更多