现在,我的组织控制器会列出当前用户拥有会员资格的所有组织。我知道我的测试是错误的,但我无法弄清楚它是如何正确的。
organizations_controller.rb
def index
@user = current_user
@organizations = @user.organizations.all
end
这样工作正常,模型正常,视图显示正确的组织。
我正在尝试为它编写测试,但不知怎的,我被卡住了。这是我的工厂:
factory :organization do
name "example"
website "www.aquarterit.com"
after(:create) {|organization| organization.users = [create(:admin)]}
end
这是我的测试:
describe "GET #index" do
it "populates an array of organizations where the user has membership" do
organization = create(:organization)
get :index
expect(assigns(:organizations)).to eq([organization])
end
it "renders the :index view" do
get :index
expect(response).to render_template ("index")
end
end
结果很自然:
expected: [#<Organization id: 1, name: "example", website: "www.aquarterit.com", created_at: "2014-02-20 22:10:17", updated_at: "2014-02-20 22:10:17">]
got: nil
(compared using ==)
答案 0 :(得分:0)
这是因为您在测试中创建的organization
与调用user
时返回的current_user
无关。存根current_user
方法以返回您的用户
describe "GET #index" do
it "should populate an array of organizations where the user has membership" do
organization = create(:organization)
controller.stub(:current_user).and_return(organization.user)
get :index
expect(assigns(:organizations)).to eq([organization])
end
it "renders the :index view" do
get :index
expect(response).to render_template ("index")
end
end