Rails与Rspec和Factory Girl有关

时间:2012-06-08 12:25:43

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

我正在尝试使用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>

规格/ 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

规格/模型/ 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

应用程序/控制器/ 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

应用程序/控制器/ users_controller.rb

class UsersController < ApplicationController
  .
  .
  .

  def new
     @user = User.new
  end

  .
  .
  .
end

应用程序/模型/ user.rb

class User < ActiveRecord::Base
  belongs_to :client

  .
  .
  .
end

应用程序/模型/ client.rb

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

end

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在您的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